TreeView控件实践
TreeView控件可以通过HierarchicalDataTemplate 和 DataTemplate来自定义。
1)HierarchicalDataTemplate用来支持HeaderedItemsControl,其中DataType指定当前的数据类型, 只有符合这个类型才使用HierarchicalDataTemplate;ItemsSource用来指定ItemsHost;内部的自定义实现(TextBlock)指定当前数据类型如何渲染,注意:不是子节点。
<HierarchicalDataTemplate DataType = "{x:Type src:League}"
ItemsSource = "{Binding Path=Divisions}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
ItemsSource = "{Binding Path=Divisions}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
2)对于TreeView控件, 我们可以只指定一个HierarchicalDataTemplate, 而保证数据结构每层的ItemSource的类型名一样, 每层的数据层需要渲染的数据一样。
public class Node
{
public string Name {get; set;}
public string Id {get; set;}
public List<Node> Nodes {get; set;}
}
{
public string Name {get; set;}
public string Id {get; set;}
public List<Node> Nodes {get; set;}
}
<HierarchicalDataTemplate ItemsSource = "{Binding Path=Nodes}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
3)另外一种就是如1)所示, 我们可以针对每层的数据层指定HierarchicalDataTemplate,
<Window x:Class="SDKSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="HierarchicalDataTemplate Sample"
xmlns:src="clr-namespace:SDKSample">
<DockPanel>
<DockPanel.Resources>
<src:ListLeagueList x:Key="MyList"/>
<HierarchicalDataTemplate DataType = "{x:Type src:League}"
ItemsSource = "{Binding Path=Divisions}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType = "{x:Type src:Division}"
ItemsSource = "{Binding Path=Teams}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type src:Team}">
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
</DockPanel.Resources>
<Menu Name="menu1" DockPanel.Dock="Top" Margin="10,10,10,10">
<MenuItem Header="My Soccer Leagues"
ItemsSource="{Binding Source={StaticResource MyList}}" />
</Menu>
<TreeView>
<TreeViewItem ItemsSource="{Binding Source={StaticResource MyList}}" Header="My Soccer Leagues" />
</TreeView>
</DockPanel>
</Window>
https://muzizongheng.blog.csdn.net/