#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.

        <CollectionViewSource x:Key="cvsActors" Source="{Binding ActorList}" >
                <scm:SortDescription PropertyName="LastName" />

        <ListBox Name="lbActors" Margin="15" Width="200" Height="190"
                 ItemsSource="{Binding Source={StaticResource cvsActors}}"/>

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