Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 983
user436862 Avatar asked Jun 06 '13 15:06

user436862


1 Answers

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}}"/>
like image 182
Thomas Levesque Avatar answered Oct 31 '22 23:10

Thomas Levesque