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.

First we need sample data
to load into DataGrid, let's have a Class called Employee which is
having the following properties.
public class Employee
{
public string Name { get; set; }
public string Contact { get; set; }
public string EmailID { get; set; }
public string Country { get; set; }
}
Now in the Constructor we
will have some sample data and bind to DataGrid.
public Window1()
{
InitializeComponent();
ObservableCollection empData = new ObservableCollection
{
new Employee{Name="Diptimaya Patra", Contact="0000",
EmailID="diptimaya.patra@some.com", Country="India"},
new Employee{Name="Dhananjay Kumar", Contact="00020",
EmailID="dhananjay.kumar@some.com", Country="India"},
new Employee{Name="David Paul", Contact="1230",
EmailID="david.paul@some.com", Country="India"},
new Employee{Name="Christina Joy", Contact="1980",
EmailID="christina.joy@some.com", Country="UK"},
new Employee{Name="Hiro Nakamura", Contact="0000",
EmailID="hiro.nakamura@some.com", Country="Japan"},
new Employee{Name="Angela Patrelli", Contact="0000",
EmailID="angela.patrelli@some.com", Country="Japan"},
new Employee{Name="Zoran White", Contact="0000",
EmailID="diptimaya.patra@some.com", Country="Scotland"},
};
ListCollectionView collection = new ListCollectionView(empData);
collection.GroupDescriptions.Add(new PropertyGroupDescription("Country"));
dgData.ItemsSource = collection;
}
}
Now that we have Sample
data let's see how does it look like.

Looks good to proceed.
Now
we will create a Style that will hold the Grouped Data.
To use it in DataGrid, use
the following XAML inside DataGrid.
Now go back to C# code
behind and add the Grouping definitions.
ListCollectionView collection = new ListCollectionView(empData);
collection.GroupDescriptions.Add(new PropertyGroupDescription("Country"));
dgData.ItemsSource = collection;
Now we are ready to test our
application.

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.
Now let's test the
application.

Now we can expand and
collapse any Grouped Item.
you can also download the sample project used the above example.
Hope this article helps.