简体   繁体   中英

WPF - changing bound data according to other controls

I'm trying to experiment with WPF, so I created some test window to see how it goes. I got a window which holds a combo box with some options, and in the window there's a data grid which is bound to a property of a list of the combo box's selected item (meaning when you select an item in the combo box, the data grid is updated accordingly).

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

I've added a CheckBox and a TextBox to the window and I want to use them in order to filter some lines in the data grid. The checkBox determines if there is any filtering at all, and the filtering itself is done according to the text in the TextBox.

How Do I filter the DataGrid's lines with the CheckBox and TextBox? I know I can make a MultiValueConverter with MultiBinding and return the new ItemsSource I want for the DataGrid, but I'm looking for other solutions.

allItemsYou can bind the Filter-Properties of the Object that contains the DataGrid-Lines to the CheckBox and TextBox. Every time these Properties are updated, you update the filtering too. Additional you implement the INotifyPropertyChanged Interface and and raise the PropertyChanged Event every time the List of DataGrid-Lines changes.

The class you bind to would look something like this:

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM