wpf - 为 DataGridTemplateColumn 指定数据上下文
问题描述
DataGrid 绑定到 List,其中 T 具有多个嵌套属性(以及其他属性)。
class T
{
public X PropertyX {get;}
public Y PropertyY {get;}
public Z PropertyZ {get;}
}
class X { public A SomeProperty {get;}}
class Y { public A SomeProperty {get;}}
class Z { public A SomeProperty {get;}}
X、Y 和 Z 类具有 A 类型的相同属性 SomeProperty。
我需要分别显示 PropertyX、PropertyY 和 PropertyZ 的 SomeProperty 的数据。
所以,我需要这样的东西:
<DataGridTemplateColumn DataContext="{Binding X.A}" CellTemplate="{StaticResource CommonTemplate}" />
<DataGridTemplateColumn DataContext="{Binding Y.A}" CellTemplate="{StaticResource CommonTemplate}" />
<DataGridTemplateColumn DataContext="{Binding Z.A}" CellTemplate="{StaticResource CommonTemplate}" />
显然DataGridTemplate列没有DataContext,所以我想知道这可能吗?CommonTemplate 相当大,我想重用它。
有任何想法吗?
解决方案
您可以在另一个 DataTemplate 中重用现有的 DataTemplate,该 DataTemplate 也指定了 DataContext:
<DataGridTemplateColumn Header="x">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding PropertyX.SomeProperty}"
ContentTemplate="{StaticResource CellTemplate}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="y">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding PropertyY.SomeProperty}"
ContentTemplate="{StaticResource CellTemplate}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
推荐阅读
- firebase - 如何firebase ml vision将每一行存储到一个变量中
- webpack - 带有 webpack 的 Aframe - 系统 [名称] 不是构造函数
- javascript - 如果我不知道值的长度,如何限制变量以获取字符串中的特定值?
- c++ - C++ 无法处理大型布尔数组
- python - 如何阅读此列表理解
- salesforce - Salesforce 机会 API 金额的变量值
- wordpress - 如何从当前主页获取所有子页面
- php - Facebook 图形 API PHP 和 cURL
- docker - 访问 docker 容器内的外部读卡器(智能卡读卡器、nfc 读卡器等)设备
- c - 我想访问 C 中另一个结构字段中的通用结构字段