user436862
user436862

Reputation: 869

How to bind column header to property in ViewModel? (WPF MVVM)

I Have window that have DataContext that is bind to ViewModel object (VM1 for the example). VM1 have a lot of properties and one of them is a string that called "MyTitle".

I have a DataGridTextColumn in 'Window\Grid\DataGrid'. How can I bind the property "Header" in DataGridTextColumn to the Property "MyTitle" in my VM1 ViewModel?

Thanks!

Upvotes: 9

Views: 7264

Answers (3)

BionicCode
BionicCode

Reputation: 28968

There is no need to use a binding proxy, like too often suggested. Obviously, DataGridColumn.Header is not a DependencyProperty. To still bind it, simply define the Header explicitly using XAML property element syntax, and bind the header content:

<DataGrid>
  <DataGrid.Columns>
    <DataGridTextColumn>
      <DataGridTextColumn.Header>
        <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.TextValue}" />
      </DataGridTextColumn.Header>
    </DataGridTextColumn>
  </DataGrid.Columns>
</DataGrid>

Upvotes: 2

Neil B
Neil B

Reputation: 2224

The accepted answer didn't work for me.

I was able to make this work.

<FrameworkElement x:Name="proxy" DataContext="{Binding}"/>

<DataGridTextColumn Header="{Binding Source={x:Reference proxy}, Path=DataContext.MyTitle}/>

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292405

Unfortunately, the column definitions of the DataGrid don't inherit the DataContext, because they're not part of the visual tree, so you can't bind directly to the ViewModel. You need to resort to a workaround such as the one described in this article:

<DataGrid.Resources>
    <local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>

...

<DataGridTextColumn Header="{Binding Data.MyTitle, Source={StaticResource proxy}}"/>

Upvotes: 25

Related Questions