【问题标题】:Specifying data context for DataGridTemplateColumn为 DataGridTemplateColumn 指定数据上下文
【发布时间】:2020-07-19 02:55:49
【问题描述】:

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 挺大的,我想复用一下。

有什么想法吗?

【问题讨论】:

    标签: wpf xaml datagrid datatemplate


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-02-22
      • 2013-07-30
      • 2017-07-06
      • 2012-04-09
      • 1970-01-01
      • 2012-10-13
      • 2014-08-12
      • 1970-01-01
      • 2016-05-23
      相关资源
      最近更新 更多