如何将列标题绑定到ViewModel中的属性? (WPF MVVM) [英] How to bind column header to property in ViewModel? (WPF MVVM)

查看:374
本文介绍了如何将列标题绑定到ViewModel中的属性? (WPF MVVM)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有DataContext绑定到ViewModel对象的窗口(例如,VM1)。
VM1有很多属性,其中一个是一个名为MyTitle的字符串。



我在Window\Grid\中有一个DataGridTextColumn DataGrid'。如何将DataGridTextColumn中的属性Header绑定到VM1 ViewModel中的属性MyTitle?



谢谢!

解决方案

不幸的是, 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}}"/>

这篇关于如何将列标题绑定到ViewModel中的属性? (WPF MVVM)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆