1

My question is similar to Why DataColumn.Caption doesn't work?, but for WPF. I have a DataGrid bound to a DataTable using an MVVM pattern. The DataGrid has AutoGenerateColumns = true. How do I bind the DataGridColumn header text to the DataColumn.Caption instead of DataColumn.ColumnName? I was hoping for a solution like this:

<DataGrid ItemsSource="MyDataTable" AutoGenerateColumns="true">
    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Text="{Binding DataColumn.Caption}"> <!--this does not work-->
...
</DataGrid>
Community
  • 1
  • 1
zambonee
  • 1,599
  • 11
  • 17

2 Answers2

0

I ended up solving this issue in the code behind.

private void dgResults_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    e.Column.Header = tableResults.Columns[e.PropertyName].Caption;
}
zambonee
  • 1,599
  • 11
  • 17
0

When you bind your DataTable to DataGrid.ItemSource you usually provide its DefaultView whose type is DataView. You can use its Table property to access columns on that view properly casting values.

private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    e.Column.Header = ((sender as DataGrid).ItemsSource as DataView).Table.Columns[e.PropertyName].Caption;
}