#984 – Grouping Items in a ListBox with a CollectionViewSource

Similar to how you can use a CollectionViewSource to sort a collection of items in a ListBox, you can also use the CollectionViewSource to group the items, based on a property on the underlying object that you’re binding to.

Assume that you have an Actor object that has a LastName property and a DecadeBorn property that indicates what decade an actor was born in.  You can group the actors by decade and then sort within each decade by last name as shown below.

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

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

The empty GroupStyle element will cause the group to be rendered using a string representation of the DecadeBorn property.

We sort by decade and by last name within each decade.