如何将列标题绑定到 ViewModel 中的属性?(WPF MVVM) [英] How to bind column header to property in ViewModel? (WPF MVVM)
问题描述
我有一个窗口,该窗口具有绑定到 ViewModel 对象(例如 VM1)的 DataContext.VM1 有很多属性,其中之一是名为MyTitle"的字符串.
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".
我在WindowGridDataGrid"中有一个 DataGridTextColumn.如何将 DataGridTextColumn 中的属性Header"绑定到 VM1 ViewModel 中的属性MyTitle"?
I have a DataGridTextColumn in 'WindowGridDataGrid'. How can I bind the property "Header" in DataGridTextColumn to the Property "MyTitle" in my VM1 ViewModel?
谢谢!
推荐答案
不幸的是,DataGrid
的列定义没有继承 DataContext
,因为它们是不是可视化树的一部分,因此您不能直接绑定到 ViewModel.您需要采用一种解决方法,例如 这篇文章:
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}}"/>
这篇关于如何将列标题绑定到 ViewModel 中的属性?(WPF MVVM)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!