动态更改 WPF Datagrid 列标题
我在 wpf win 应用程序中使用 wpf 工具包数据网格。在我的视图模型中,我有一个 observablecollection 属性,它绑定到数据网格的 itemsource 。 学生班级具有姓名、年龄、班级属性,并显示在网格的每一列中。
但是我的视图模型类中有一个名为“Header1”的属性,如何将其绑定到数据网格文本列的标题?当我使用时,它不会在网格中显示标题字符串。我需要在运行时更新此列标题。我怎样才能做到这一点?我也尝试了以下方法;
<dg:DataGridColumn Header = "{Binding Header1, ElementName=MyUsrCtrl}" />
但这也不起作用?我也使用了 DataContext.Header1, ElementName=MyUsrCtrl
...但没有用。
怎么可能?
I am using wpf toolkit datagrid in wpf win applications. In my view model, I have a observablecollection property which is binded to the itemsource of the datagrid.
Student class is having Name, Age, Class properties and displays in each columns in the grid.
But I have a property called "Header1" in my View model class and how i can bind it to the Header of the data grid text column ? When I used, it is not displaying the header string in the grid. I need to update this column header at run time. How I can do that ? I also tried the following way;
<dg:DataGridColumn Header = "{Binding Header1, ElementName=MyUsrCtrl}" />
BUT this is also not working ? I used DataContext.Header1, ElementName=MyUsrCtrl
also...but no use.
How it is possible ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法绑定到任何 daatgrid 列,因为它们不是可视化树的一部分。使用代理元素技巧。
WPF 错误:找不到目标元素的管理 FrameworkElement
You cannot bind to any daatgrid columns as they are not part of the visual tree. Use the proxy element trick.
WPF Error: Cannot find governing FrameworkElement for target element
在不太了解您的代码的情况下,我只是尝试一下,但我们开始吧。我假设您已使用
DataContext
将整个视图绑定到视图模型,并且正在为DataGrid
绑定ItemsSource
内容像这样:假设这是真的,那么您的标头绑定就完成了大部分工作。只需删除绑定的 ElementName 部分,如下所示:
这应该可以解决问题。另一件需要注意的事情是确保您的视图模型实现 INotifyPropertyChanged 并且
Header1
属性的 setter 调用您的PropertyChanged
方法。Without knowing much about your code, I'm just taking a stab at this, but here we go. I'm assuming you've bound your entire view to your view model using
DataContext
, and that you're bindingItemsSource
for theDataGrid
something like this:Assuming that's true, you're most of the way there with your header binding. Just remove the ElementName portion of the binding like so:
That should do the trick. One other thing to note is to make sure that your view model implements INotifyPropertyChanged and that the setter for the
Header1
property calls yourPropertyChanged
method for itself.