Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 207
sailorstar165 Avatar asked Oct 17 '25 15:10

sailorstar165


1 Answers

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>
like image 110
sailorstar165 Avatar answered Oct 20 '25 05:10

sailorstar165



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!