且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将列标题绑定到ViewModel中的属性? (WPF MVVM)

更新时间:2022-10-21 09:44:58

不幸的是, DataGrid 的列定义不会继承 DataContext ,因为它们不是视觉树的一部分,所以你不能直接绑定到ViewModel。您需要诉诸一种解决方法,例如这篇文章

 < DataGrid。资源> 
< local:BindingProxy x:Key =proxyData ={Binding}/>
< /DataGrid.Resources>

...

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


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!

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}}"/>