使用CompositeCollection的TreeView,展开未显示的箭头

时间:2013-04-30 16:37:55

标签: c# wpf treeview compositecollection

我有一个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);

问题是每当我运行代码时,只显示第一个和第二个,但第二个旁边没有展开箭头,并且无法展开。调试显示g2将g3作为子节点,但它不存在于TreeView控件中。

我该如何解决?目的是尽可能少地使用代码,我尽量避免添加抽象层和包装类的负载......

通过这些,没有解决我的问题:

1 个答案:

答案 0 :(得分:1)

我能够通过源代码中的以下修改来解决问题:

Class 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 Treeview Databinding Hierarchal Data with mixed types建议的内容,我不得不摆脱MyGroup中的两个单独的列表(它们为不同类型的对象标准化),并且只使用一个CompositeCollection,然后添加子项到子项列表,不管子对象的类型。