Tuesday, February 12, 2008

CollectionView Filter

For those of you who have worked with data collections in WPF if you have probably learned how helpful a CollectionView can be. CollectionViews let you filter, group and sort a collection of data without any requiring of the data. Setting a CollectionView up to filter or group data is actually pretty easy. Here is an example of how you would setup a Collection into a CollectionView to be filtered.

ListCollectionView _view; 

public Window1() 

{ 
     InitializeComponent(); 

     string[] myValues = new string[] { "Red Car", "Red Truck", "Blue Car", "Yellow Truck" }; 
     _view = new ListCollectionView(myValues); 
     this.DataContext = _view; 
} 

private void FilterTrucks(Object sender, RoutedEventArgs args) 
{ 

	if (_view.CanFilter && (ShowTrucks.IsChecked == true)) 
		_view.Filter = new Predicate<object>(IsValueTruck); 
	else 

	{ 
		 // Remove the filter 
		 _view.Filter = null; 
	} 

} 

public bool IsValueTruck(Object value) 

{ 
     return (value.ToString().Contains("Truck")); 
} 



You can see that when the "Show only Trucks" checkbox is check the list is automatically filtered to show only items that are trucks. You do not need to write any code that refreshes the UI this is all handled for you by the WPF binding and the ListCollectionView. You can try changing the ListCollectionView to just a CollectionView. If you do this you will see that the UI does not refresh the list when the check box is selected. This is because CollectionView itself does not handle the UI level view update. You can use ListCollectionView, CollectionViewSource or BindingListCollectionView (this type is used for binding and filtering ADO.net objects like datasets) to filter and bind to lists. We have covered ListCollectionView binding and filter. In future posts I will cover the other types as well as how to set up grouping and sorting.

No comments: