Wednesday, January 15, 2014

#986 – Filtering a ListBox Using a CollectionViewSource

When populating a ListBox from a CollectionViewSource, you can also filter the data.  Below is an example of a ListBox that is bound to a CollectionViewSource.

<Window.Resources>
    <CollectionViewSource x:Key="cvsActors" Source="{Binding ActorList}" >
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="LastName" />
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</Window.Resources>
 
<StackPanel>
    <ListBox Name="lbActors" Margin="15" Width="200" Height="200"
             ItemsSource="{Binding Source={StaticResource cvsActors}}"/>
    <CheckBox Content="Only Joans" IsChecked="{Binding OnlyJoans}"
              Margin="15"/>
</StackPanel>

In code, we add a handler for the Filter event of the CollectionViewSource.  The handler is called for each item in the list.