#985 – Displaying Expandable Groups within a ListBox

You can group items in a ListBox using a CollectionViewSource.  You can then set the GroupStyle property of the ListBox to be an Expander control so that the groups can be expanded and collapsed.

In the example below, we group a collection of Actors by the decade of their birth.

    <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>
                    <GroupStyle.ContainerStyle>
                        <Style TargetType="{x:Type GroupItem}">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate>
                                        <Expander Header="{Binding Name}" IsExpanded="True">
                                            <ItemsPresenter />
                                        </Expander>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </GroupStyle.ContainerStyle>
                </GroupStyle>
            </ListBox.GroupStyle>
        </ListBox>
    </StackPanel>

We can now expand and collapse the groups representing an actor’s birth decade.

985-001

 

985-002

Advertisements