TreeViewItem添加节点

时间:2016-10-05 14:15:58

标签: c# wpf

我以编程方式将节点添加到WPF树视图的尝试没有按预期工作,即,对于下面的代码,我希望在“C1-4”和“C2-”下有叶节点“C14-5和”C14-6“ 4“而它们出现在根节点”Level-0“

之下

public class CSTree 
{
    public class CS_TREE
    {
        int nodeId; int parentId, string description;
        public CS_TREE(int node, int parent, string desc)
        {
            nodeId = node; parentId = parent; description = desc;
        }
        public int NodeId { get { return nodeId;}
        public int ParentId { get { return parentId;}
        public int Description { get { return description;}
    }

private static List<CS_TREE> tree = new List<CS_TREE>() new { new CS_TREE(1,0,"Level-0"), new CS_TREE(2,1,"Level-1 A"), new CS_TREE(3,1,"Level-1 B"), new CS_TREE(4,1,"Level-1 C"), new CS_TREE(5,4,"Level-2 C1-4"), new CS_TREE(6,4,"Level-2 C2-4"), new CS_TREE(7,5,"Level-3 C14-5"), new CS_TREE(7,6,"Level-3 C24-6"), } public void PopulateTreeView() { foreach (CS_TREE cst in L_tree) { AddToTree(cst); } } public void AddToTree(CS_TREE cst) { var subitem = new TreeViewItem() { Header = cst.Description, Tag = cst}; if (cst.ParentId == 0) { _rootNode = new TreeViewItem() { Header = cst.Description, Tag = cst }; } else { TreeViewItem node = FindNode(_rootNode, cst); if (node != null) { node.Items.Add(subitem); } else { _rootNode.Items.Add(subitem); } } } private TreeViewItem FindNode(TreeViewItem rootNode, CS_TREE cst) { TreeViewItem rv = null; if (rootNode != null && rootNode.HasItems) { var items = rootNode.Items; foreach (TreeViewItem item in items) { CS_TREE nodeCST = item.Tag as CS_TREE; if (nodeCST.NodeId == cst.ParentId) { return item; } else if (item.HasItems) { FindNode(item, cst); } } } return rv; } private TreeViewItem _rootNode = null; public TreeViewItem Root { get { return _rootNode; } }

}

读者可否指出我正确的方向?

1 个答案:

答案 0 :(得分:0)

您需要返回找到的节点。 而不是

FindNode(item, cst);

DO

rv = FindNode(item, cst);
if (rv != null)
    return rv;

此外,您在节点中使用相同的NodeId 7&#34; C14-5&#34;和&#34; C24-6&#34;。

因此,如果你想要&#34; C24-6&#34;下的任何节点,你应该写

new CS_TREE(8,6,"Level-3 C24-6"),