This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Data Binding - Collection Views - Filtering Data

The one hundred and fifth part of the Windows Presentation Foundation Fundamentals tutorial expands upon the previous article, which described collection views. This article manipulates collection views using C# code to apply sorting, grouping and filtering of the data.

Filtering a CollectionView

To filter the data in a collection view you can provide a predicate to the Filter property. Often the predicate will be defined as a lambda expression or a method that returns a Boolean value. The predicate is applied to every item in the collection in turn. Where it returns false, the item is not included in the view.

When you change the Filter property, the view is updated, the predicate checked and the results filtered. If the function is based upon a value that can change, rather than the entire Filter property being replaced, the filtering is not automatically reapplied when the value changes. In these cases you can call the Refresh method to reset the list.

Let's add filtering to the product options list so that only options for the selected product are visible. First, we need a way in which to obtain the selected product. We can do this by binding the SelectedItem property of the ListBox to a write-only property of the ProductData class.

Adjust the product list box's XAML, as follows. This binds SelectedItem to the SelectedProduct property.

<ListBox Grid.Row="1" ItemsSource="{Binding Products}"
    SelectedItem="{Binding SelectedProduct,Mode=OneWayToSource}"

Now we can add the SelectedProduct property to the ProductData class. We don't need to store the value provided, we'll just use it to set up a new filter. We'll use a lambda expression that compares the selected product's code against the product codes from the list of options. Where the codes match, the option will be included.

NB: There are better ways to implement this type of master-detail view using features that we have not yet seen in the WPF tutorial.

public Product SelectedProduct
        if (value != null)
            ProductOptionsView.Filter = o => ((ProductOption)o).ProductCode == value.Code;

Run the program for a final time to see the results. When the window first loads, both lists are fully populated. This is because the selected product has not yet been set, so no filter has been applied. As you select items from the product list, the options will be refreshed accordingly.

WPF CollectionView filtering

19 October 2014