Add a Footer Row to a Silverlight 3 DataGrid

November 02, 2009

A missing feature in the Silverlight 3 DataGrid is the ability to add a footer row.  For example, if you were trying to create a timesheet application using Silverlight, you’d want to be able to show the total number of hours for each day as shown in the image below.

image

The solution that I came up with is slightly hack-y but definitely works.  Rather than relying on the DataGrid to provide a footer, create your own UserControl that snaps a footer row on to the bottom of the grid using a StackPanel.

                                                                                                                                                                                                                                                                                                                                               

Ok.  So what do you do when the DataGrid’s columns get re-sized?  Basically, how do you keep the footer cells aligned and sized to match the columns in the DataGrid?  The answer is pretty easy.  Once you have the DataGrid and the supporting footer controls added to the StackPanel, you can create an event handler that attaches to the DataGrid’s LayoutUpdated event so that you can keep the footer columns.  Whenever the LayoutUpdated event fires, iterate over the columns in the DataGrid and set the corresponding footer cell control width to the same value.

private void SyncColumnWidths(DataGrid source, Grid target)
{
if (source == null || target == null)
{
return;
}

if (target.ColumnDefinitions.Count == source.Columns.Count)
{
for (int i = 0; i < target.ColumnDefinitions.Count; i++)
{
target.ColumnDefinitions[i].Width = new GridLength(source.Columns[i].ActualWidth);
}
}
}

Click here to view a running online sample.
Click here to download the source code.

-Ben

Categories: silverlight-3