Using different templates for different levels of the tree
i want to Display a treeview bound to a Model It works but:
<TreeView ItemsSource="{Binding Items}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}" >
<Style.Triggers>
<Trigger Property="HasItems" Value="true">
<Setter Property="Focusable" Value="False"/>
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<Hie开发者_如何学PythonrarchicalDataTemplate ItemsSource="{Binding SubNodes}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<CheckBox Grid.Column="0"/>
<TextBlock Text="{Binding Text}" Grid.Column="1"/>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
I want to have three Templates : one for the rootitem , a second for the subnodes and a third for subnodes but alternative to the other template.
Its relatively simple.
Define three different types to which the tree is bound:
// defines root nodes in the tree
public sealed class RootNode : ITreeNode // or some other interface or base type
{
public IEnumerable<SubNode> SubNodes {get;set;}
}
// defines all middle nodes
public class SubNode : ITreeNode
{
public IEnumerable<SubNode> Children {get;set;}
}
// defines leafs
public sealed class LeafNode : SubNode { }
Construct them and add them to your ViewModel
public sealed class ViewModel
{
// or use an OC<T> or whatever your design needs
public IEnumerable<RootNode> Roots {get;set;}
Then use HierarchicalDataTemplate.DataType to designate the template for each:
<TreeView
ItemsSource="{Binding Roots}">
<TreeView.Resources>
<HierarchicalDataTemplate
xmlns:t="clr-namespace:NamespaceForNodeClasses"
DataType="{x:Type t:RootNode}
ItemsSource="{Binding SubNodes}">
<TextBlock Text="I'm a root node!"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate
xmlns:t="clr-namespace:NamespaceForNodeClasses"
DataType="{x:Type t:SubNode}
ItemsSource="{Binding Children}">
<TextBlock Text="I'm a regular tree node!"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate
xmlns:t="clr-namespace:NamespaceForNodeClasses"
DataType="{x:Type t:LeafNode}>
<TextBlock Text="I'm a leaf!"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
精彩评论