Grouping in Datagrid in WPF


Introduction

In this article we will see how to have Grouped rows in DataGrid in WPF.

Crating WPF Application Project

Fire up Visual Studio 2008 and Create a WPF Application and name the project as GroupingDataGridWPF.

WPFGrouping1.gif

First we need sample data to load into DataGrid, let's have a Class called Employee which is having the following properties.

WPFGrouping2.gif

Now in the Constructor we will have some sample data and bind to DataGrid.

WPFGrouping3.gif

Now that we have Sample data let's see how does it look like.

WPFGrouping4.gif

Looks good to proceed.

Now we will create a Style that will hold the Grouped Data.

WPFGrouping5.gif

To use it in DataGrid, use the following XAML inside DataGrid.

WPFGrouping6.gif

Now go back to C# code behind and add the Grouping definitions.

WPFGrouping7.gif

Now we are ready to test our application.

WPFGrouping8.gif

Yes, we have achieved grouping. Now we need to have Expand and Collapse functionality of the Group Header.

So in the Style defined for GroupItem let's add an Expander control.

WPFGrouping9.gif

Now let's test the application.

WPFGrouping10.gif

Now we can expand and collapse any Grouped Item.

Hope this article helps.