Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding DataColumn.Caption to DataGrid Header

Tags:

mvvm

wpf

xaml

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>
like image 974
zambonee Avatar asked Jun 29 '26 13:06

zambonee


1 Answers

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;
}
like image 197
JasurbekDavronov Avatar answered Jul 01 '26 12:07

JasurbekDavronov