如何将DataGridTemplateColumn.Visibility绑定到DataGrid.ItemsSource之外的属性? [英] How to bind DataGridTemplateColumn.Visibility to a property outside of DataGrid.ItemsSource?
问题描述
我需要将 DataGridTemplateColumn
的 Visibility
绑定到 DataGrid.ItemsSource
,因为我需要将所有行中的此列绑定到 ViewModel
中的一个属性,但据我所知只需将它绑定到 ItemsSource
中的内容,或者您应该使用 ElementStyle
和 EditingElementStyle
我已经尝试过这个代码:
I need to bind the Visibility
of a DataGridTemplateColumn
to a property outside of the DataGrid.ItemsSource
,because i need to bind this column in the all the rows to one property inside the ViewModel
,but as far as i know you just can bind that to something inside the ItemsSource
or you should use ElementStyle
and EditingElementStyle
I've Already tried this code:
<DataGridTemplateColumn Header="post"
Visibility="{Binding DataContext.ProjectPostVisibility
, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MvvmCommonControl:DataGrid}}"/>
我确定我的绑定是正确的,因为当我绑定 DataGridCell.Visibility
如下所示:
And i'm Sure my binding is correct because it works fine when i bind the DataGridCell.Visibility
like below:
<DataGridTemplateColumn Header="post">
<DataGridTemplateColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Visibility" Value="{Binding DataContext.ProjectPostVisibility,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MvvmCommonControl:DataGrid}}"/>
</Style>
</DataGridTemplateColumn.CellStyle>
</DataGridTemplateColumn >
推荐答案
你的绑定是正确的,但它不会工作直接使用 DataGridTemplateColumn
,因为它不在视觉树中。所以它不是继承 DataContext
。
Your binding is correct, but it won't work with DataGridTemplateColumn
directly because it's not in the visual tree. So it's not inherting DataContext
.
你需要绑定 DataGridTemplateColumn
从代码后面。 这是一个演示,展示了一种方式。
You need to bind the DataGridTemplateColumn
from code behind. Here is a demo that shows a way of doing it.
这篇关于如何将DataGridTemplateColumn.Visibility绑定到DataGrid.ItemsSource之外的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!