12

I know this question has been asked before, but none of the "previous" answers seems to work for me...

I have implemented a functionality for multi languages in my application, and I therefor have to bind the header of my DataGrid columns to the DataContext.

I use a dictionary (called Text in the example below) in the DataContext to store the texts, and the binding works fine with textblocks, buttons etc.

<TextBlock Text="{Binding Text[Name], FallbackValue='Name'" />

But, I can't get this to work on the Header-attribute of the DataGrid columns.

I read somewhere, that I need to write a template for the column/header to achieve this, but I can't figure this out either.

Christian Tang
  • 1,450
  • 4
  • 19
  • 30

2 Answers2

36

You may need to walk back up the tree to get the DataContext you want:

<DataGridTextColumn Binding="{Binding Name}">
    <DataGridTextColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding DataContext.Text[Name],
                       RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
        </DataTemplate>
    </DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>

Doing this directly on the Header property will not work because it cannot be resolved in-place as the column is an abstract object not appearing in the tree.

H.B.
  • 166,899
  • 29
  • 327
  • 400
5

correct. there is no elemet in visual tree directly mapping to DataGridTextColumn so you can't use RelativeSource with AncestorType (i.e. DataGridTextColumn is not a control hence it doesn't have a parent control). below code should work fine

<DataGridTextColumn Binding="{Binding Name}">
  <DataGridTextColumn.Header>
    <TextBlock Text="{Binding DataContext.Text[Name],
                      RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
  </DataGridTextColumn.Header>
</DataGridTextColumn>
Linus Caldwell
  • 10,908
  • 12
  • 46
  • 58
bo chen
  • 51
  • 1
  • 1
  • Thanks, this is less painful than the HeaderTemplate solution, and it still works. But is there a way to do the same trick using a `Header="{Some stringified binding}"` attribute? – Adrian Ratnapala Dec 17 '13 at 11:40
  • 1
    Tried this on .NET 4.5 and 4.6 and while it sort of worked, it led to inconsistent behavior in which the `DataGrid` would not reliably update when the bound object updated. The method in the accepted answer does work consistently though. – fuglede Jul 20 '17 at 16:49