TreeView 和 TreeViewItem 控件可与 HierarchicalDataTemplate 对象一起使用以轻松显示分层数据。
创建模板
-
按升序声明模板。将 HierarchicalDataTemplate..::..ItemsSource 属性设置为子节点的数据源,并将 HierarchicalDataTemplate..::..ItemTemplate 属性设置为定义这些节点结构的模板。
<StackPanel.Resources>
<sdk:HierarchicalDataTemplate x:Key="ChildTemplate" >
<TextBlock FontStyle="Italic" Text="{Binding Path=Title}" />
</sdk:HierarchicalDataTemplate>
<sdk:HierarchicalDataTemplate x:Key="NameTemplate"
ItemsSource="{Binding Path=ChildTopics}"
ItemTemplate="{StaticResource ChildTemplate}">
<TextBlock Text="{Binding Path=Title}" FontWeight="Bold" />
</sdk:HierarchicalDataTemplate>
</StackPanel.Resources>
创建 TreeView 结构
-
创建一个 TreeView 并将其 ItemsControl..::..ItemTemplate 属性设置为最高级别的数据模板。当模板声明为资源时,最高级别的数据模板通常是最后一个声明为资源的模板。
<sdk:TreeView Width="400" Height="300" ItemsSource="{Binding}"
ItemTemplate="{StaticResource NameTemplate}" x:Name="myTreeView" />
示例
public partial class MainPage : UserControl
{
static public ObservableCollection<Topic> Topics = new ObservableCollection<Topic>();
public MainPage()
{
InitializeComponent();
Topics.Add(new Topic("Using Controls and Dialog Boxes", -1));
Topics.Add(new Topic("Getting Started with Controls", 1));
Topic DataGridTopic = new Topic("DataGrid", 4);
DataGridTopic.ChildTopics.Add(
new Topic("Default Keyboard and Mouse Behavior in the DataGrid Control", -1));
DataGridTopic.ChildTopics.Add(
new Topic("How to: Add a DataGrid Control to a Page", -1));
DataGridTopic.ChildTopics.Add(
new Topic("How to: Display and Configure Row Details in the DataGrid Control", 1));
Topics.Add(DataGridTopic);
myTreeView.DataContext = Topics;
}
}
public class Topic
{
public string Title { get; set; }
public int Rating { get; set; }
private ObservableCollection<Topic> childTopicsValue = new ObservableCollection<Topic>();
public ObservableCollection<Topic> ChildTopics {
get
{
return childTopicsValue;
}
set
{
childTopicsValue = value;
}
}
public Topic() {}
public Topic(string title, int rating)
{
Title = title;
Rating = rating;
}
}
<StackPanel x:Name="LayoutRoot" Background="White">
<StackPanel.Resources>
<sdk:HierarchicalDataTemplate x:Key="ChildTemplate" >
<TextBlock FontStyle="Italic" Text="{Binding Path=Title}" />
</sdk:HierarchicalDataTemplate>
<sdk:HierarchicalDataTemplate x:Key="NameTemplate"
ItemsSource="{Binding Path=ChildTopics}"
ItemTemplate="{StaticResource ChildTemplate}">
<TextBlock Text="{Binding Path=Title}" FontWeight="Bold" />
</sdk:HierarchicalDataTemplate>
</StackPanel.Resources>
<sdk:TreeView Width="400" Height="300" ItemsSource="{Binding}"
ItemTemplate="{StaticResource NameTemplate}" x:Name="myTreeView" />
</StackPanel>