Monday, December 30, 2013

WPF Binding of DataGrid Column Header in XAML

Dynamically binding to a column header of a DataGrid is not a transparently task. The problem is that the column header is not inheriting from FrameworkElement.

A simple solution to that problem is presented on the Developer Code Samples Gallery (Binding of DataGrid column header) and the TechNet Wiki (Binding of DataGrid Column Header).

There are several solutions for this problem. I will introduce the simplest solution (in my opinion). Since DataGridColumn does not inherit the DataContext of the superior element, you have to indicate the DataContext to use. This can be easily done as the following code snippet shows.
<DataGrid>
  <DataGrid.Columns>
    <DataGridTemplateColumn>
      <DataGridTemplateColumn.Header>
        <TextBlock Text="{Binding DataContext.HeaderNameText, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
      </DataGridTemplateColumn.Header>
    </DataGridTemplateColumn>
  </DataGrid.Columns>
<DataGrid>

As you can see the header is defined by using a TextBlock. The Text property of the TextBlock is bound to the property HeaderNameText of the DataContext of the DataGrid. In a similar way you could use your own DataContext for the DataGridColumns. By defining the header in this way you could further customize your header by using further elements, e.g. Images. The DataContext of the DataGrid is set in code.

Data data = new Data();
data.HeaderNameText = "Header2";
data.Items = new List<string>() { "Item1", "Item2" };
  
DataContext = data;

The DataContext is an own object containing the values of the DataGrid and the Header name.

public class Data
{
  public string HeaderNameText
  {
    get;
    set;
  }
  
  public List<string> Items
  {
    get;
    set;
  }
}

13 comments:

  1. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. I have tried the same but no success.. not working !!

      Delete
    2. You can find an working example on the Developer Code Samples Gallery (http://code.msdn.microsoft.com/Binding-of-DataGrid-column-73f80f68). You can use the code as starting point. But you can post your code that is not working, so I have a look at it.

      Delete
  2. Replies
    1. The header is set dynamically by binding as you can see in the post. You can find an working example on the Developer Code Samples Gallery (http://code.msdn.microsoft.com/Binding-of-DataGrid-column-73f80f68).

      Delete