【发布时间】:2013-04-30 16:37:54
【问题描述】:
我有一个 TreeView,它绑定到由 MyItem 和 MyGroup 对象组成的 CompositeCollection。
类定义:
public class MyItem
{
public string Name { get; set; }
public MyItem(string name = "")
{
Name = name;
}
}
public class MyGroup
{
public string Name { get; set; }
public List<MyGroup> MyGroups = new List<MyGroup>();
public List<MyItem> MyItems = new List<MyItem>();
public IList Children
{
get
{
return new CompositeCollection()
{
new CollectionContainer { Collection = MyGroups },
new CollectionContainer { Collection = MyItems }
};
}
}
public MyGroup(string name)
{
Name = name;
}
}
XAML:
<TreeView Name="myTreeView">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:MyGroup}" ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:MyItem}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
设置树的代码:
var root = new ObservableCollection<MyGroup>();
myTreeView.ItemsSource = root;
MyGroup g1 = new MyGroup("First");
MyGroup g2 = new MyGroup("Second");
MyGroup g3 = new MyGroup("Third");
MyItem i1 = new MyItem("Item1");
MyItem i2 = new MyItem("Item2");
MyItem i3 = new MyItem("Item3");
root.Add(g1);
root.Add(g2);
g2.MyGroups.Add(g3);
g1.MyItems.Add(i1);
问题是每当我运行代码时,只显示First和Second,但Second旁边没有展开箭头,并且无法展开。调试显示 g2 有 g3 作为子级,但它不存在于 TreeView 控件中。
我该如何解决?目的是用尽可能少的代码来完成它,我尽量避免添加大量的抽象层和包装类......
经历了这些,并没有解决我的问题:
【问题讨论】:
标签: c# wpf treeview compositecollection