sailorstar165 sailorstar165 - 3 months ago 20
C# Question

How do I bind the Header of a Datagrid to a value in a viewmodel?

I'm trying to bind a string from my viewmodel to the header of a DataGrid. Below is my .xaml code:

<DataGrid Grid.Row="0" Grid.Column="1" Style="{StaticResource CustomDataGridStyle}" ItemsSource="{Binding InputDataCollection}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="{Binding InputNameHeader}" Binding="{Binding Name}" Width="50*"
ElementStyle="{StaticResource CellTextStyleR}" HeaderStyle="{StaticResource HeaderRight}"/>
<DataGridTextColumn Header="{Binding InputStateHeader}" Binding="{Binding State}" Width="50*"
ElementStyle="{StaticResource CellTextStyleL}"/>
</DataGrid.Columns>
</DataGrid>


The problem I'm running into is that the column headers are always blank. I assume it's because I defined the ItemSource and that the things I'm binding the headers to is not part of that ItemSource.

Does anyone have any suggestions on how I can define the Headers with strings from the viewmodel in this situation?

Answer

Figured it out.

I had to move the Header binding to the DataGridTextColumn.HeaderTemplate and use RelativeSource. Now it works as it should.

<DataGrid Grid.Row="0" Grid.Column="1" Style="{StaticResource CustomDataGridStyle}" ItemsSource="{Binding InputDataCollection}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Name}" Width="50*" ElementStyle="{StaticResource CellTextStyleR}" HeaderStyle="{StaticResource HeaderRight}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding DataContext.InputNameHeader, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
                    </DataTemplate>
                </DataGridTextColumn.HeaderTemplate>
            </DataGridTextColumn>
            <DataGridTextColumn Header="Input State" Binding="{Binding State}" Width="50*" ElementStyle="{StaticResource CellTextStyleL}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding DataContext.InputStateHeader, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
                    </DataTemplate>
                </DataGridTextColumn.HeaderTemplate>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
Comments