WPF Treeview:指定TreeViewItem值成员

时间:2015-03-18 13:30:53

标签: c# .net xml wpf treeview

我需要使用XML中的数据填充Treeview。我的XML架构是:

<root>
   <node>
      <leaf>
         <displaymember>String to Display</displaymember>
         <valuemember>Value</valuemember>
      </leaf>
   </node>
   <node>
      <leaf>
         <displaymember>String to Display</displaymember>
         <valuemember>Value</valuemember>
      </leaf>
   </node>
</root>

显然,每个节点中会有许多嵌套节点和许多叶子,但叶子将始终包含displaymember和valuemember元素。

我正在使用另一个问题(How to create treeview from XML file using WPF?)中的以下代码来填充树视图:

public YourWindow()
{
    InitializeComponent();
    BuildTree(treeView, XDocument.Load(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"testxml.xml")));
}

private void BuildTree(TreeView treeView, XDocument doc)
{
    TreeViewItem treeNode = new TreeViewItem 
    {  
        //Should be Root
        Header = doc.Root.Name.LocalName,
        IsExpanded = true
    };
    treeView.Items.Add(treeNode);
    BuildNodes(treeNode, doc.Root);
}

private void BuildNodes(TreeViewItem treeNode, XElement element)
{
    foreach (XNode child in element.Nodes())
    {
        switch (child.NodeType)
        {
            case XmlNodeType.Element:
                XElement childElement = child as XElement;
                TreeViewItem childTreeNode = new TreeViewItem
                {
                    //Get First attribute where it is equal to value
                    Header = childElement.Attributes().First(s => s.Name == "value").Value ,
                    //Automatically expand elements
                    IsExpanded = true
                };
                treeNode.Items.Add(childTreeNode);
                BuildNodes(childTreeNode, childElement);
                break;
            case XmlNodeType.Text:
                XText childText = child as XText;
                treeNode.Items.Add(new TreeViewItem { Header = childText.Value, });
                break;
        }
    }
}

我可以看到第二行填充了TreeViewItem的显示成员(Header)。我不确定如何填充它的相应值成员。

我很欣赏如何实现这一目标的建议。

0 个答案:

没有答案