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




About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #984 – Grouping Items in a ListBox with a CollectionViewSource

  1. Pingback: Dew Drop – January 10, 2014 (#1699) | Morning Dew

  2. Andrei Rinea says:

    You’ve got a typo in the title and URL, “souorce”.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: