我想你也必須爲「靜態」節點創建HierarchicalDataTemplate
。而且,由於一個HierarchicalDataTemplate
的的ItemsSource希望集合,你可以用XAML創建這些集合類似這樣的
命名空間
xmlns:coll="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
集合
<coll:ArrayList x:Key="MapCollection">
<sys:String>Maps</sys:String>
</coll:ArrayList>
<coll:ArrayList x:Key="TableCollection">
<sys:String>Tables</sys:String>
</coll:ArrayList>
<coll:ArrayList x:Key="FieldCollection">
<sys:String>Fields</sys:String>
</coll:ArrayList>
這種解決方案的問題是,當你設置例如MapCollection作爲的ItemsSource爲HierarchicalDataTemplate
,您將無法訪問到一個新的水平Maps
集合屬性,所以你必須爬上可視化樹得到它保持像
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}},
Path=DataContext.Maps}"
使用這種方法,你HierarchicalDataTemplate
S能像這樣
<!-- Field Templates -->
<HierarchicalDataTemplate x:Key="FieldsTemplate">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="FieldTemplate"
ItemTemplate="{StaticResource FieldsTemplate}"
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}},
Path=DataContext.Fields}">
<TextBlock Text="{Binding}"/>
</HierarchicalDataTemplate>
<!-- Table Templates -->
<HierarchicalDataTemplate x:Key="TablesTemplate"
ItemTemplate="{StaticResource FieldTemplate}"
ItemsSource="{Binding Source={StaticResource FieldCollection}}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="TableTemplate"
ItemTemplate="{StaticResource TablesTemplate}"
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}},
Path=DataContext.Tables}">
<TextBlock Text="{Binding}"/>
</HierarchicalDataTemplate>
<!-- Map Templates -->
<HierarchicalDataTemplate x:Key="MapsTemplate"
ItemTemplate="{StaticResource TableTemplate}"
ItemsSource="{Binding Source={StaticResource TableCollection}}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="MapTemplate"
ItemTemplate="{StaticResource MapsTemplate}"
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}},
Path=DataContext.Maps}">
<TextBlock Text="{Binding}"/>
</HierarchicalDataTemplate>
<!-- Project Template -->
<HierarchicalDataTemplate x:Key="ProjectDataTemplate"
ItemTemplate="{StaticResource MapTemplate}"
ItemsSource="{Binding Source={StaticResource MapCollection}}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
的TreeView
<TreeView Name="treeView"
ItemTemplate="{StaticResource ProjectDataTemplate}"
ItemsSource="{Binding Projects}"/>
非常感謝您睦h爲您的解決方案和翔實的解釋!這很好! – 2011-02-13 16:18:24