#984 – Grouping Items in a ListBox with a CollectionViewSource
January 10, 2014 3 Comments
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.
<Window.Resources> <CollectionViewSource x:Key="cvsActors" Source="{Binding ActorList}" > <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="DecadeBorn" /> <scm:SortDescription PropertyName="LastName" /> </CollectionViewSource.SortDescriptions> <CollectionViewSource.GroupDescriptions> <data:PropertyGroupDescription PropertyName="DecadeBorn"/> </CollectionViewSource.GroupDescriptions> </CollectionViewSource> </Window.Resources> <StackPanel> <ListBox Name="lbActors" Margin="15" Width="200" Height="240" ItemsSource="{Binding Source={StaticResource cvsActors}}"> <ListBox.GroupStyle> <GroupStyle/> </ListBox.GroupStyle> </ListBox> </StackPanel>
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.