Adding Sorting and Filtering

Although our sample object is fairly simple, real-world objects are often much more complicated. It’s therefore useful to be able to sort the properties so that the user can easily find the one they want, and to be able to filter them so that the user can quickly home in on a specific property that they know the name of.

Adding Sorting

In this example, we offer the option to sort by property name in ascending or descending order. To do this, call CollectionViewSource.GetDefaultView(grid.BindingView), where grid is the instance of the PropertyGrid control, to get an ICollectionView. Then apply a SortDescription to the ICollectionView, specifying Node.Name or Node.HumanName as the property to sort on. For example:

CopySorting the properties by name
 1ICollectionView view = CollectionViewSource.GetDefaultView(PropertyGrid.BindingView);
 4string sortBoxText = (SortBox.SelectedItem as ComboBoxItem).Content as string;
 6if (sortBoxText == "Ascending")
 8  view.SortDescriptions.Add(new SortDescription("Node.HumanName", ListSortDirection.Ascending));
10else if (sortBoxText == "Descending")
12  view.SortDescriptions.Add(new SortDescription("Node.HumanName", ListSortDirection.Descending));

You can also use the PropertyGrid.Sorting property to control sorting, though this requires an IComparer instead of a SortDescription.

Adding Filtering

In this example, we allow the user to filter the grid to show only those properties whose name contains a given string. To do this, get an ICollectionView for the grid in the same way as for sorting, and set its Filter property. In the example, the Filter callback performs a case-insensitive, culture-sensitive check of both the Node.Name and Node.HumanName properties against the string entered by the user.

The filter definition looks like this:

CopyDefining the filter
 1if (String.IsNullOrEmpty(filterText))
 3  SetPropertyGridFilter(null);
 7  SetPropertyGridFilter(delegate(object obj)
 8    {
 9      Node node = ((PropertyGridRow)obj).Node;
10      return node.Name.IndexOf(filterText, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
11        node.HumanName.IndexOf(filterText, StringComparison.CurrentCultureIgnoreCase) >= 0;
12    });

The filter is applied to the PropertyGrid control as follows:

CopyApplying the filter
1ICollectionView view = CollectionViewSource.GetDefaultView(PropertyGrid.BindingView);
2view.Filter = filter;

See 02_AddingSortingAndFiltering.xaml in the PropertyGridCustomization project.

Next step: Editing Custom Types