Silverlight, UI Design, XAML

Bind a list of items to an accordion control with grouping

My model looks like this:


public sealed class ReportItem
{

public string Name { get; set; }
public string Description { get; set; }
public string GroupName { get; set; }

}

I want to display these reports in an accordion control, where the items are grouped by the
GroupName property. The group name would be the accordion header buttons, and under each
accordion group would appear the items containing that group name.

You’ll need a CollectionViewSource:


<navigation.Page ... xmlns:data="clr-namespace:System.Windows.Data;assembly=System.Windows"

 

	<navigation:Page.Resources>
		<data:CollectionViewSource x:Key="ReportsViewSource" Source="{Binding Reports}">
			<data:CollectionViewSource.GroupDescriptions>
				<PropertyGroupDescription PropertyName="GroupName" />
			</data:CollectionViewSource.GroupDescriptions>
		</data:CollectionViewSource>
	</navigation:Page.Resources>

I’m using a model object so my report collection is a property called Reports.

The GroupName is the property I am grouping by.

		<toolkit:Accordion ItemsSource="{Binding BindsDirectlyToSource=True, Source={StaticResource ReportsViewSource}, Path=View.Groups}" Grid.Row="1" HorizontalAlignment="Left" Name="accordion1" Width="315" VerticalAlignment="Stretch">
			<toolkit:Accordion.ContentTemplate>
				<DataTemplate>
					<ListBox ItemsSource="{Binding Items}" BorderThickness="0"><!-- this is the Group.Items -->
						<ListBox.ItemTemplate>
							<DataTemplate>
								<TextBlock FontWeight="Bold" Text="{Binding Name}" /><!-- this is the Report.Name -->
							</DataTemplate>
						</ListBox.ItemTemplate>
					</ListBox>
				</DataTemplate>
			</toolkit:Accordion.ContentTemplate>
			<toolkit:Accordion.ItemTemplate>
				<DataTemplate>
					<TextBlock Text="{Binding Name}" /><!-- this is the Group.Name -->
				</DataTemplate>
			</toolkit:Accordion.ItemTemplate>
		</toolkit:Accordion>


ReportsViewSource is my CollectionViewSource. The property View contains some objects, like Items for the items without grouping.
The property Groups contains a collection of Groups, each with a Name and Items property. The accordion’s ItemTemplate defines the
headers, while the ContentTemplate defines the content to go into each accordion. Here I am using a ListBox to display the subitems.