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>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With