0

I am trying to initiate a DataGrid in C#/WPF and have the text of the respective column headers bind to a value in the ViewModel. However, this does not seem to work. Here is the xaml for the DataGrid:

      <DataGrid ItemsSource="{Binding Measurements}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Timestamp}" Width="Auto">
                    <DataGridTextColumn.Header>
                        <TextBlock Foreground="Black" Text="{Binding Text_Header1}"/>
                    </DataGridTextColumn.Header>
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>

And here is the value in my ViewModel

public string Text_Header1 { get { return local.Header1Text; } }

All the other Databinding for the DataGrid works just fine. It's just the title of the headers that doesn't seem to work.

I tried changing the Text property to a non-binding value and that one shows. So this seems to be the right way to set the text. I also tried having the Text_Header1 just return "Test" or bind it to other values that I know word in other elements and that did not work either. The column header just appears as empty when the Binding is set.

I have also tried setting the Binding up like this

<TextBlock Text="{Binding Text_Time, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" Foreground="Black"/>

and it has also not worked. The header stays blank.

  • Of which viewmodel does Text_Header1 belong to? – Radu Hatos Mar 03 '23 at 09:09
  • If the binding property for the header does not exists in the same data contexts as the one given to the DataGridView then you need to specify it. It should be Text="{Binding DataContext.Text_Header1, RelativeSource={ RelativeSource AncestorType=Name_of_control}}" – Radu Hatos Mar 03 '23 at 09:14
  • It is the ViewModel of the View. It is the same data context as the other bindings in the view, which all work. – Jonas Herz Mar 03 '23 at 09:33

0 Answers0