-1

I have a datagrid whose column headers I would like to change during runtime. I have tried something like this but doesn't work

    <DatagridTextColumn Header="{Binding Path=MyNewHeader}" Binding=" {Binding Path=MyBindingProperty}" />

And In my MVVM

    string myHeaderProperty;
    public string MyHeaderProperty{
    get{
    return myHeaderProperty 
    }
    set{
    Set(ref myHeaderProperty, value);
    }

But does not work. Any Ideas will be greatly appreciated

KMarto
  • 300
  • 2
  • 23
  • 2
    Possible duplicate of [WPF datagrid header text binding](https://stackoverflow.com/questions/1658397/wpf-datagrid-header-text-binding) – ASh Oct 04 '17 at 08:05
  • Doesn't work. What would be `DataContext[0].DisplayName` in the view model? Can XAML be able to translate `DataContext[0]`? I just have a simple property in ViewModel like so `string column1;` `public string Column1{ get{...} set{...} }` – KMarto Oct 04 '17 at 09:12
  • try this https://stackoverflow.com/a/45430214/1292254 – Zafar Oct 04 '17 at 09:28

2 Answers2

1

This should work provided that MyHeaderProperty belongs to the DataContext of the parent DataGrid, i.e. the view model:

<DataGridTextColumn Binding="{Binding MyBindingProperty}">
    <DataGridTextColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=DataContext.MyHeaderProperty, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
        </DataTemplate>
    </DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>
mm8
  • 163,881
  • 10
  • 57
  • 88
0

If you take a look in the output window you will see that you probably get a binding expression exception because MyNewHeader is not a property on you item in the row.

So you need to bind it to the parent via relativesource binding

Take a look at the following example https://wpftutorial.net/BindingExpressions.html

Jordy van Eijk
  • 2,718
  • 2
  • 19
  • 37