【问题标题】:How to inline DataTemplate of a nested property?如何内联嵌套属性的 DataTemplate?
【发布时间】:2016-07-25 07:06:27
【问题描述】:

假设我有:

class Employee
{
    public string Name;
    public string Id;
    // ...
}

<DataTemplate DataType="local:Employee"> ... </DataTemplate>

和:

class Manager
{
    public string Salary;
    public int Rank;
    public Employee DirectReport;
}

在引用Employee DataTemplate 的同时,如何为Manager 编写DataTemplate

即:

<DataTemplate DataType="local:Manager">
   <TextBlock Text={Binding Salary}/>
   <TextBlock Text={Binding Rank}/>
   // How do I display the DirectReport here using Employee's DataTemplate?

</DataTemplate>

【问题讨论】:

    标签: wpf binding


    【解决方案1】:

    您可以通过简单的 OO 继承来实现这一点,而不是使用 WPF 进行任何棘手的操作。

    Manager 仍然是 Employee,所以像这样改变你的类:

    public class Employee
    {
        public string Name;
        public string Id;
        public string Salary;
        Employee DirectReport;
        // ...
    }
    
    public class Manager : Employee
    {   
        public int Rank;   
    }
    

    然后您可以保留您的 WPF DataTemplate 原样。

    或者,您可以使用 ContentControl 从 ManagerTemplate 中引用 EmployeeTemplate 定义:

    <DataTemplate DataType="local:Manager">
        <TextBlock Text={Binding Salary}/>
        <TextBlock Text={Binding Rank}/>
    
        <ContentControl ContentTemplate="{StaticResource EmployeeTemplate}" /> 
    </DataTemplate>
    

    其他有用的参考资料有:

    【讨论】:

    • 谢谢,但在我的场景中继承并不适合。我正在努力显示具有复合对象属性的复合对象。而不是写一个巨大的 DataTemplate 我希望我可以写多个小的并引用它们
    猜你喜欢
    • 2016-06-02
    • 2014-01-08
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多