树视图与复合收集,展开箭头不显示

本文关键字:显示 视图 复合 | 更新日期: 2023-09-27 18:11:28

我有一个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控件中。

我该如何修复它?目的是用尽可能少的代码完成,我尽量避免添加抽象层和包装类的负载…

看了这些,没有解决我的问题:

  • 混合类型的WPF树视图数据绑定层次数据

  • http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode

树视图与复合收集,展开箭头不显示

我能够通过在源代码中进行以下修改来解决这个问题:

组类MyGroup:

public class MyGroup
{
    public string Name { get; set; }
    private IList children = new CompositeCollection() {
                new CollectionContainer { Collection = new List<MyGroup>() },
                new CollectionContainer { Collection = new List<TestItem>() }
    };
    public IList Children
    {
        get { return children; }
        set { children = value; }
    }
    public MyGroup(string name)
    {
        Name = name;
    }
}

设置树的代码:

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.Children.Add(g3);
g1.Children.Add(i1);

因此,尽管WPF树视图数据绑定层次数据混合类型的建议,我不得不摆脱MyGroup中的两个单独的列表(代表不同类型的对象),并只使用一个CompositeCollection,然后将子项目添加到Children列表中,而不管子对象的类型。