HierarchicalDataTemplate
有一個DataType
屬性,因此您使用它來指定類型,就像您爲DataTemplate
所做的那樣。比方說,你換你的層次結構的視圖模型:
public class MyViewModel
{
public List<classC> Items { get; set; }
}
然後創建您的層次結構如下所示:在XAML
this.DataContext = new MyViewModel
{
Items = new List<classC>
{
new classC
{
name = "Class C",
subItems = new List<classB> {
new classB{
name = "Class B1",
subItems = new List<classA>{
new classA {name="Class A1a"},
new classA {name="Class A1b"},
new classA {name="Class A1c"},
}
},
new classB{
name = "Class B2",
subItems = new List<classA>{
new classA {name="Class A2a"},
new classA {name="Class A2b"},
new classA {name="Class A2c"},
}
}
}
}
}
};
然後,所有你需要做的就是相關的DataTemplates和HierarchicalDataTemplates添加到您的TreeView的資源塊:
<TreeView ItemsSource="{Binding Items}">
<TreeView.Resources>
<DataTemplate DataType="{x:Type local:classA}" >
<TextBlock Text="{Binding name}" Foreground="Blue" />
</DataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:classB}" ItemsSource="{Binding subItems}" >
<TextBlock Text="{Binding name}" Foreground="Green" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:classC}" ItemsSource="{Binding subItems}" >
<TextBlock Text="{Binding name}" Foreground="Red" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
結果:
您是否嘗試過使用DataTemplateSelector?你可以在你的HierarchicalDataTemplate中使用它,然後選擇你想要的任何你想要的dataTemplate。檢查了這一點:http://dotnetbeyond.blogspot.pt/2011/08/wpf-how-to-display-different-category.html – sexta13