我想知道如何将自定义数据类型绑定到TreeView. 数据类型基本上是包含其他arraylists的对象的arraylist.访问将看起来像这样: foreach (DeviceGroup dg in system.deviceGroups) { foreach (DeviceType dt in dg.d
数据类型基本上是包含其他arraylists的对象的arraylist.访问将看起来像这样:
foreach (DeviceGroup dg in system.deviceGroups) { foreach (DeviceType dt in dg.deviceTypes) { foreach (DeviceInstance di in dt.deviceInstances) { } } }
我希望TreeView看起来像这样:
DeviceGroup1
--> DeviceType1 --DeviceInstance1 --DeviceInstance2 --> DeviceType2 --DeviceInstance1
DeviceGroup2
--> DeviceType1 --DeviceInstance1 --> DeviceType2好的,这是
HierarchicalDataTemplate
将为您节省的地方.诀窍是你需要使用两个不同的分层模板,因为你在这里有一个三级层次结构.我构建了一个简单的UserControl来说明.首先,这里有一些代码隐藏创建类似于你拥有的模型数据:
public partial class ThreeLevelTreeView : UserControl { public ArrayList DeviceGroups { get; private set; } public ThreeLevelTreeView() { DeviceInstance inst1 = new DeviceInstance() { Name = "Instance1" }; DeviceInstance inst2 = new DeviceInstance() { Name = "Instance2" }; DeviceInstance inst3 = new DeviceInstance() { Name = "Instance3" }; DeviceInstance inst4 = new DeviceInstance() { Name = "Instance4" }; DeviceType type1 = new DeviceType() { Name = "Type1", DeviceInstances = new ArrayList() { inst1, inst2 } }; DeviceType type2 = new DeviceType() { Name = "Type2", DeviceInstances = new ArrayList() { inst3 } }; DeviceType type3 = new DeviceType() { Name = "Type3", DeviceInstances = new ArrayList() { inst4 } }; DeviceType type4 = new DeviceType() { Name = "Type4" }; DeviceGroup group1 = new DeviceGroup() { Name = "Group1", DeviceTypes = new ArrayList() { type1, type2 } }; DeviceGroup group2 = new DeviceGroup() { Name = "Group2", DeviceTypes = new ArrayList() { type3, type4 } }; DeviceGroups = new ArrayList() { group1, group2 }; InitializeComponent(); } } public class DeviceGroup { public string Name { get; set; } public ArrayList DeviceTypes { get; set; } } public class DeviceType { public string Name { get; set; } public ArrayList DeviceInstances { get; set; } } public class DeviceInstance { public string Name { get; set; } }
这里没什么难的,但请注意,如果要动态添加和删除集合,则应使用ObservableCollection而不是ArrayList.现在让我们看看这个控件的XAML:
<UserControl x:Class="TestWpfApplication.ThreeLevelTreeView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestWpfApplication" DataContext="{Binding RelativeSource={RelativeSource Self}}"> <TreeView ItemsSource="{Binding DeviceGroups}"> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding DeviceTypes}"> <HierarchicalDataTemplate.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding DeviceInstances}"> <TextBlock Text="{Binding Name}"/> </HierarchicalDataTemplate> </HierarchicalDataTemplate.ItemTemplate> <TextBlock Text="{Binding Name}"/> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView>
这是结果:
alt text http://img684.imageshack.us/img684/6281/threeleveltreeview.png