2016-07-24 97 views
0

假設我有:如何內嵌嵌套屬性的DataTemplate?

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

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

和:

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

我怎麼會寫DataTemplateManager雖然提到EmployeeDataTemplate

即:

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

</DataTemplate> 

回答

1

你用簡單的OO inhertance而不是什麼花招與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> 

其他有用的參考資料包括:

+0

謝謝,但在我的sc enario繼承不太合適。我正在努力的是顯示覆合對象,其中包含複合對象的屬性。我不希望寫一個巨大的DataTemplate,而是希望能寫出多個小數據並引用它們。 – Shmoopy

+0

@Shmoopy我已經更新了我的答案。 – slugster