WPF:将DataGrid列标题绑定到ViewModel [英] WPF: Binding DataGrid column header to ViewModel

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

问题描述

我有一个datagrid我手动指定列(AutoGenerateColumns =false)。我使用MVVM,我想绑定列标题(文本),以便我从我的ViewModel中获取它。但是我找不到一个办法。



最近我发现的是:
Wpf工具包。将DataGrid列标题绑定到DynamicResource
...这是一个技巧,您可以使用该技巧将列标题绑定到在XAML中静态声明的字符串。但是我需要从我的ViewModel中获取它。



我想要这样做的原因是我要用作列标题的文本将显示在整个GUI。要确保它实际上是一样的,我想要在代码中可用。我不能将这些字符串存储在XAML资源文件中,因为我还需要在代码中访问这些字符串。



我正在使用TeleRik的RadGridView,但是猜猜我会有同样的问题,如果我的标准网格视图。



任何提示赞赏!谢谢!

解决方案

在Silverlight中,我尝试了以下内容:

 < DataGridTextColumn Header ={Binding ElementName = LayoutRoot,Path = DataContext.MyProperty}... /> (LayoutRoot是Window / UserControl中的第一个控件,MyProperty是VM中的一个)



$ b它不起作用,因为列无法访问视觉树。



可能值得一试在WPF与您的网格。


I have a datagrid in which i manually specify the columns (AutoGenerateColumns="false"). I'm using MVVM and I would like to bind the column header (the text) so that I get it from my ViewModel. But I can't find a way to do that.

The closest thing I've found is this: Wpf Toolkit. Bind DataGrid Column Header to DynamicResource ...which is a "trick" with which you can bind the column header to a string statically declared in XAML. But I need to get it from my ViewModel.

The reason I want to this is that the text I want to use as column header will be shown in several places throughout the GUI. To get make sure it actually is the same everywhere I want to have it available in code. And I can't store the strings in a XAML resource file because I also need access to these strings in code.

I'm using a RadGridView from TeleRik, but I guessing I'd have the same problem if I the standard gridview.

Any tips appreciated! Thanks!

解决方案

In Silverlight I have tried the following:

<DataGridTextColumn Header="{Binding ElementName=LayoutRoot, Path=DataContext.MyProperty}" ... />

(LayoutRoot is the first control in the Window/UserControl, MyProperty is something in the VM) It does not work because the column has no access to the visual tree.

It may be worth a try in WPF with your Grid.

这篇关于WPF:将DataGrid列标题绑定到ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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