Wednesday, August 25, 2010

Synchronizing group row headers with column headers in Silverlight DataGrid

Grouping in the DataGrid in Silverlight is quite easy. What is not so obvious is how to change the caption of the column name on the group row. It turns out that you could use the LoadingRowGroup of the DataGrid:
theGrid.LoadingRowGroup += (s, e) =>
{
   e.RowGroupHeader.PropertyName = "A custom caption";
}
The original value of the e.RowGroupHeader.PropertyName is the PropertyName of the PropertyGroupDescription. Using this value the column header can be determined:
private string GetColumnCaption(DataGrid grid, string columnName)
{
   if (grid == null || String.IsNullOrEmpty(columnName))
   {
       return null;
   }
   foreach (DataGridBoundColumn column in grid.Columns)
   {
       if (column == null)
       {
           continue;
       }
       Binding binding = column.Binding;
       if (binding == null)
       {
           continue;
       }
       if (binding.Path.Path == columnName)
       {
           return Convert.ToString(column.Header);
       }
   }
   return null;
}
Read more: On developing Pochet.NET