Filtering listbox data in WPF

Every now and then we’ll need to display items in a ListBox (or other ItemsControl) which we can filter.

One might simply create two ObservableCollections, one containing all items and the other being the filtered items. Then bind the ItemsSource from the ListBox to the filtered items list.

A simple alternate would be to use a CollectionView, for example

public class MyViewModel
{
   public MyViewModel()
   {
      Unfiltered = new ObservableCollection<string>();
      Filtered = CollectionViewSource.GetDefaultView(Unfiltered);
   }

   public ObservableCollection<string> Unfiltered { get; private set; }
   public ICollectionView Filtered { get; private set; }
}

Now to filter the collection view we can use the following (this is a silly example which will filter to show only strings larger than 3 in length)

Filtered.Filter = i => ((string)i).Length > 3;

to remove the filter we can just assign null to it, thus

Filtered.Filter = null;

In use, all we need to do is bind our Filtered property, for example in a ListBox control’s ItemsSource property and then apply a filter or remove a filter as required.