WPF - 根据其他控件更改绑定数据

时间:2014-03-15 15:12:50

标签: c# wpf data-binding datagrid

我正在尝试使用WPF,因此我创建了一些测试窗口以了解它是如何进行的。 我有一个窗口,其中包含一个带有一些选项的组合框,并且在窗口中有一个数据网格,该数据网格绑定到组合框所选项目列表的属性(这意味着当您选择一个项目时在组合框中,数据网格相应更新)。

<DataGrid Grid.Row="1" AutoGenerateColumns="True"
          ItemsSource="{Binding ElementName=comboBoxPeople, 
                                Path=SelectedItem.OrdersList}"/>

我已经在窗口中添加了CheckBox和TextBox,我想使用它们来过滤数据网格中的某些行。 checkBox确定是否有任何过滤,过滤本身是根据TextBox中的文本完成的。

如何使用CheckBox和TextBox过滤DataGrid的行?我知道我可以使用MultiBinding创建一个MultiValueConverter并返回我想要的DataGrid的新ItemsSource,但我正在寻找其他解决方案。

1 个答案:

答案 0 :(得分:0)

allItems您可以将包含DataGrid-Lines的Object的Filter-Properties绑定到CheckBox和TextBox。每次更新这些属性时,您也会更新过滤。 另外,您实现INotifyPropertyChanged接口,并在每次DataGrid-Lines列表更改时引发PropertyChanged事件。

你绑定的类看起来像这样:

class Class1 : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
            private List<OrderItem> allItems;

    private string textBoxValue;
    public string TextBoxValue
    {
        get { return textBoxValue; }
        set
        {
            textBoxValue = value;
            updateList();
        }
    }

    private List<OrderItem> orderItems;
    private List<OrderItem> OrderItems
    {
        get { return orderItems; }
        set
        {
            orderItems= value;
            PropertyChanged(this, new PropertyChangedEventArgs("OrderItems"));
        }
    }

    private void updateList()
    {
        List<OrderItem> newList = new List<OrderItem>();
        //update the List
        foreach (OrderItem orderItem in allItems)
        {
            if (orderItem[name] == textBoxValue) newList.Add(orderItem);
        }
        OrderItems= newList;
    }
}
相关问题