WPF树形视图,带有不同类别下的子节点

3

给定以下类Foo

class Foo {
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

给定一个 `List`,其中 `Property1` 是一种类别,因此集合中多个 Foo 实例具有相同的 `Property1` 值。在这种情况下,`Property2` 是唯一的,但这不是相关的。
我想在 WPF 中使用 TreeView 显示 Foo 集合,在每个独特的 `Property1` 上它都会显示一个节点(以 `Property1` 的值作为标头)。作为该节点的子项,它应该具有所有具有该 `Property1` 的 Foo 实例,并且应该将 `Property2` 作为标头。
到目前为止,我尝试过 `HierarchicalDataTemplate` 方法(更喜欢)和代码后端,但两者似乎都没有我想要的结果。以下是我尝试的代码:
private void ReloadTree() {
    var uniqueProperty1 = foos
        .Select(f => f.Property1)
        .Distinct();

    var result = new List<TreeViewItem>();
    
    foreach (var prop1 in uniqueProperty1) {
        var item = new TreeViewItem();
        item.Header = name;
        item.IsExpanded = false;
    
        var attributes = new List<Foo>();

        foreach (var foo in attributes) {
            var subItem = new TreeViewItem();
            subItem.Header = foo.Property2;

            item.Items.Add(subItem);
        }

        bindingsTree.Items.Add(item);
    }
}

foosFoo 的集合,bindingsTreeTreeView 时。任何帮助将不胜感激!

编辑

为了澄清以下是 foos 的列表:

var list = new List<Foo>()
{
    new Foo() { Property1 = "category1", Property2 = "A" },
    new Foo() { Property1 = "category1", Property2 = "B" },
    new Foo() { Property1 = "category2", Property2 = "C" },
    new Foo() { Property1 = "category2", Property2 = "D" },
};

结果应该是这样的:
+category1
    - A
    - B
+category2
    - C
    - D
1个回答

2
创建一个分层模型类型:
class FooViewModel
{
    public string Category { get; set; }
    public IEnumerable<FooViewModel> Children { get; set; }
}

Property1 将组 foos 进行分组:

private void ReloadTree()
{
    var categories = foos
        .GroupBy(x => x.Property1)
        .Select(x => new FooViewModel { Category = x.Key, Children = x.Select(y => new FooViewModel() { Category = y.Property2 }).ToArray() })
        .ToArray();

    bindingsTree.ItemsSource = categories;
}

XAML:

<TreeView x:Name="bindingsTree">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Category}" />
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

谢谢,这个很好用。我想太多了-_- - larzz11

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接