#983 – Using a CollectionViewSource to Sort Items in a ListBox

You can sort items within a ListBox using a CollectionViewSource, which is a wrapper around a view of a collection.  The CollectionViewSource provides support for sorting, filtering and grouping items in the underlying collection.  It provides a mechanism for configuring the view from XAML.

In the example below, we define a CollectionViewSource that wraps a collection of Actor objects and specifies a property to sort on (the actor’s last name).  Our ListBox then binds to the CollectionViewSource rather than to the collection.

    <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="190"
                 ItemsSource="{Binding Source={StaticResource cvsActors}}"/>
    </StackPanel>

983-001
The Actor objects in our ListBox are now sorted by their LastName. (LastName is a property of the Actor object).
983-002