假设我有以下数据:
<XmlDataProvider x:Key="Values">
<x:XData>
<folder name="C:">
<folder name="stuff" />
<folder name="things" />
<folder name="windows">
<folder name="system32" />
</folder>
</folder>
</x:XData>
</XmlDataProvider>
如何将其纳入树视图?我似乎无法理解分层绑定...
我知道我可以在C#代码中使用它,但我想用绑定表达式来实现它。
答案 0 :(得分:5)
编辑:没有看到您只想在XAML中执行此操作。 This MSDN帖子可以帮助您。
如果您的数据已经是分层形式,那么 HierarchicalDataTemplate
并不是那么糟糕。假设您使用以下代码将XML数据转换为模型类:
public partial class TreeViewHierarchy : Window
{
public ObservableCollection<Folder> Folders
{
get;
set;
}
public TreeViewHierarchy()
{
Folder system32 = new Folder() { Name = "system32" };
Folder windows = new Folder() { Name = "windows",
Children = new ObservableCollection<Folder>() { system32 } };
Folder things = new Folder() { Name = "things" };
Folder stuff = new Folder() { Name = "stuff" };
Folder c = new Folder() { Name = "C:",
Children = new ObservableCollection<Folder>() { stuff, things, windows } };
Folders = new ObservableCollection<Folder>() { c };
InitializeComponent();
}
}
public class Folder
{
public string Name
{
get;
set;
}
public ObservableCollection<Folder> Children
{
get;
set;
}
}
然后,TreeView
的XAML就像这样简单:
<Window x:Class="TestWpfApplication.TreeViewHierarchy"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TreeViewHierarchy" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TreeView ItemsSource="{Binding Folders}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
结果:
alt text http://img191.imageshack.us/img191/7841/treeviewhierarchy.png