Grouping in Silverlight DataGrid

Silverlight 3 Beta has got a very good response at Mix 09 conference. There have been some additions to datagrid since Silverlight 2 RTW. One of them is support for Grouping – developers can specify columns by which they want to group by.

The Group definitions can be added through XAML as well as through Code.

Adding Group Definitions through xaml

<UserControl x:Class="GroupingQuickStart.MainPage"

xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"

xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

xmlns:compmod="clr-namespace:System.Windows.Data;assembly=System.ComponentModel"

Width="700" Height="700">

<Grid x:Name="LayoutRoot" Background="White">

<data:DataGrid x:Name="dg" >

<data:DataGrid.GroupDescriptions>

<compmod:PropertyGroupDescription PropertyName="Department" />

<compmod:PropertyGroupDescription PropertyName="City" />

</data:DataGrid.GroupDescriptions>

</data:DataGrid>

</Grid>

</UserControl>

In the above example we are grouping data on “Department” column and then by "City" column. PropertyGroupDescription class in the System.Widows.Data namespace of System.ComponentModel assembly takes care of this.

Before, we see how we add grouping through code, we should make a note of PagedCollectionView class. This implements the IPagedCollectionView interface and allows grouping, sorting, etc… on the data collection. The most common way of populating data in a pagedcollectionview class is through a collection object like list that implements IEnumerable

Adding Group Descriptions through Code

We can add grouping through code in two ways

Defining group descriptions on the PagedCollectionView

PagedCollectionView collectionView = new PagedCollectionView(PopulateData(100));

collectionView.GroupDescriptions.Add(new PropertyGroupDescription("Department"));

collectionView.GroupDescriptions.Add(new PropertyGroupDescription("City"));

dg.ItemsSource = collectionView;

Defining group descriptions on the datagrid

List<Employee> list = PopulateData(100);

dg.GroupDescriptions.Add(new PropertyGroupDescription("Department"));

dg.GroupDescriptions.Add(new PropertyGroupDescription("City"));

dg.ItemsSource = list;

PopulateData method that I used in the above code snippet populates a list collection with Employee Class objects. The Employee class implements INotifyPropertyChanged and exposes the following properties

public String FirstName;

public String LastName;

public String City;

public String Department;

public String State;

datagridgrouping

Hooking up these code pieces together and building the application and running it will show us groups in datagrid.