首页 > 解决方案 > 为 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 相当大,我想重用它。

有任何想法吗?

标签: wpfxamldatagriddatatemplate

解决方案


您可以在另一个 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>

推荐阅读