This method must be credited to an article by BriOnH, "Grouping Rows in a DataGrid." I have made very minor modifications to the code (mostly renaming). The grouping effect is achieved after the DataGrid has been databound, by iterating through the DataGridItems and comparing the grouping column's item value with the value in the item above it. If they are the same then the rowspan of the cell above is increased and the current item cell is hidden.
Listing1: Grouping the Rows
public int GroupColumn(DataGrid dg, int ColumnIndex)
{
int ItemIndex = 0;
int Groupings = 0;
foreach (DataGridItem dgi in dg.Items)
{
if (dgi.ItemIndex > 0)
{
//if current cells text is the same as the cell above it
//make it invisible and increase the row span by 1 of the
//last visible cell in that column.
if (dgi.Cells[ColumnIndex].Text ==
dg.Items[dgItem.ItemIndex-1].Cells[ColumnIndex].Text)
{
dgi.Cells[ColumnIndex].Visible = false;
dg.Items[ItemIndex].Cells[ColumnIndex].RowSpan =
dg.Items[ItemIndex].Cells[ColumnIndex].RowSpan + 1;
Groupings++;
}
else if (dg.Items[dgItem.ItemIndex-1].Cells[ColumnIndex].Visible)
{
ItemIndex = dgi.ItemIndex;
}
else
{
dg.Items[ItemIndex].Cells[ColumnIndex].RowSpan =
dg.Items[ItemIndex].Cells[ColumnIndex].RowSpan + 1;
ItemIndex = dgi.ItemIndex;
}
}
}
dg.Items[dg.Items.Count-1].Visible = false;
return Groupings;
}