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?
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>
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