我需要将平面结构转换为分层结构。我的架构如下:
我得到每个项目的级别和父项,并希望将此结构添加到可观察集合中以在我的 xaml 中加载菜单控件
=======
项目1
--子项1
--ChildItem2
项目2
--ChildItem3
----------子项7
--ChildItem4
----------子项8
第 3 项
--ChildItem5
--ChildItem6
---------------ChildItem9
在 C# 中执行此操作的简单方法是什么?
您可以像这样创建层次结构:
class Item
{
public List<Item> Childs {get; set;}
// other properties and methods
}
如果您需要具有不同类型的子对象的更复杂的层次结构,您可以使用复合模式:http ://en.wikipedia.org/wiki/Composite_pattern
这并不容易。我一直在编写 Winforms 树视图。有几块代码,它们都很大。
我创建了一个名为 ParentItem 的类,在 ParentItem 中有一个名为 Children 的 ParentItem(s) 的集合。简而言之,每个元素都必须能够包含其自身的更多实例的列表。
所以在某些时候你可能会看到这样的代码:
ParentNode x1 = new ParentNode(1, "Item1"); // constructor contains record Id field and descriptive text
x1.Children.Add(new ParentNode(1, "ChildItem1"); // under the presumption the record Id is for a different table
x1.Children[0].Children[0].Add(new ParentNode(7, "ChildItem7"); // third level, not 5th level as in your example
当你向树视图控件添加节点时,你会将子节点附加到子节点的子节点上。
这是一个简单的想法,实际的实现要复杂得多。