Bindable DataGrid Columns

Currently the WPF DataGrid supports two ways in which to generate columns: AutoGenerate and XAML declaration. AutoGenerating columns will produce a column for every property in the ItemsSource class, but the behavior can be altered by using the AutoGeneratingColumn event on DataGrid. Instead of autogenerating columns, they can be declared and bound in XAML.

This was not enough for me. I want to be able to bind to a list in my view model that represents the columns I want to show. I also wanted my columns to use the items in this list as a DataContext so that I could have a column header with interesting behavior. For example, each column could have a context menu with a unique DataContext. To this end I wrote some code so that a DataGrid can be declared like:

<DataGrid 
     t:DataGridColumns.DisplayColumns="{Binding Columns}"
     ItemsSource="{Binding Rows}"
     AutoGenerateColumns="False">
  <t:DataGridColumns.ColumnSettingsTemplate>
    <DataTemplate>
      <t:DataGridColumnSettings 
          ColumnBindingPath="{Binding ColumnPath}">
        <t:DataGridColumnSettings.Header>
          <TextBlock Text="{Binding Header}"/>
        </t:DataGridColumnSettings.Header>
      </t:DataGridColumnSettings>
    </DataTemplate>
  </this:DataGridColumns.ColumnSettingsTemplate>
</DataGrid>

Each item in the Columns list is bound to a DataGridColumnSettings. In this example, the column Header is set to a TextBlock. This can be used to customize the column headers. The items in the DisplayColumn list become the DataContext for the column headers. If the Header just needs to be text, the DataGridColumnSettings can simply be declared like:

<t:DataGridColumnSettings 
         ColumnBindingPath="{Binding ColumnPath}"
         Header="{Binding Header}"/>

Currently this will only create DataGridTextColumns, but it could be extended to create DataGridComboBoxColumns and DataGridCheckBoxColumn. Get the code here. Leave the copyright on it if you want to use it.

This entry was posted in C#, WPF. Bookmark the permalink.

6 Responses to Bindable DataGrid Columns

Comments are closed.