给定以下类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);
}
}
当 foos
是 Foo
的集合,bindingsTree
是 TreeView
时。任何帮助将不胜感激!
编辑
为了澄清以下是 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