WPF中将Dictionary<T,T>类型做为数据源绑定到TreeView上
一、后台源码
using System.Collections.ObjectModel;
namespace WpfTreeView
{
public partial class MainWindow : Window
{
Dictionary<string, Node> mDicList;
public MainWindow()
{
InitializeComponent();
mDicList = new Dictionary<string, Node>();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; i++)
{
Node node = new Node(i.ToString(), "node" + i);
mDicList.Add(i.ToString(), node);
for (int j = 0; j < 5; j++)
{
Node childNode = new Node(j.ToString(), "subNode" + j);
node.Children.Add(childNode);
for (int k = 0; k < 5; k++)
{
Node grandSonNode = new Node(k.ToString(), "grandSon" + k);
childNode.Children.Add(grandSonNode);
}
}
}
treeView1.ItemsSource = mDicList;
}
}
public class Node
{
public Node(string id, string desc)
{
this.id = id;
this.desc = desc;
}
private string id;
public string ID
{
get { return id; }
set { id = value; }
}
private string desc;
public string Desc
{
get { return desc; }
set { desc = value; }
}
private ObservableCollection<Node> children = new ObservableCollection<Node>();
public ObservableCollection<Node> Children
{
get { return children; }
set { children = value; }
}
}
}
二、Xaml
<Window x:Class="WpfTreeView.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfTreeView"
Title="MainWindow" Height="646" Width="1058" Loaded="Window_Loaded">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="302*" />
<ColumnDefinition Width="10*" />
<ColumnDefinition Width="724*" />
</Grid.ColumnDefinitions>
<GridSplitter Grid.Column="1" Grid.ColumnSpan="1" HorizontalAlignment="Stretch" Name="gridSplitter1" VerticalAlignment="Stretch" Width="10" />
<TreeView HorizontalAlignment="Stretch" Name="treeView1" VerticalAlignment="Stretch" Background="#FFADABAB">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Value.Children}">
<TextBlock Text="{Binding Value.Desc}"/>
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Desc}"/>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
三、效果图
四、说明
treeView1.ItemsSource = mDicList;必须放在为mDicList添加元素之后,否则无法显示。一级节点对应的数据类型是KeyValuePair<string,Node>,子节点或孙子节点类型则是Node。