WPF - 将一个节点添加到树视图并将其另存为XML

时间:2011-05-14 17:34:57

标签: c# wpf xml treeview

我有以下代码打开XML文件并将其绑定到TreeView,但如何将子节点或父节点添加到所选节点?谢谢。

<Window.Resources>
    <HierarchicalDataTemplate x:Key="NodeTemplate">
        <HierarchicalDataTemplate.ItemsSource>
            <Binding XPath="child::*" />
        </HierarchicalDataTemplate.ItemsSource>
        <TextBlock Text="{Binding Path=Name}" />
    </HierarchicalDataTemplate>
    <XmlDataProvider x:Key="xmlDataProvider"></XmlDataProvider>
</Window.Resources>
<Grid>
    <TreeView Margin="0,24,0,143"
              Name="treeView1"
              Background="AliceBlue"
              ItemsSource="{Binding Source={StaticResource xmlDataProvider}, XPath=*}"
              ItemTemplate= "{StaticResource NodeTemplate}"/>

    <DockPanel Height="59"
               Name="dockPanel1"
               VerticalAlignment="Bottom"
               Background="AliceBlue"></DockPanel>
    <DockPanel Height="23"
               Name="dockPanel2"
               VerticalAlignment="Top"
               Background="AliceBlue">
        <Button Height="23"
                Name="button1"
                Width="75"
                Click="button1_Click">Open</Button>
    </DockPanel>
</Grid>

Button1事件:

            Microsoft.Win32.OpenFileDialog open = new Microsoft.Win32.OpenFileDialog();
            open.Filter = "XML Files (*.xml)|*.xml";
            if (open.ShowDialog(this) == true)
            {
                XmlDocument x = new XmlDocument();
                x.Load(open.FileName);
                XmlDataProvider dataProvider = this.FindResource("xmlDataProvider") as XmlDataProvider;
                dataProvider.Document = x;
            }

1 个答案:

答案 0 :(得分:0)

这样的事情:

XmlNode selected_xNode = treeView1.SelectedItem as XmlNode;
if (selected_xNode != null)
{
    XmlNode parent_xNode = selected_xNode.ParentNode;
    if (parent_xNode != null)
    {
        XmlElement new_xElement = selected_xNode.OwnerDocument.CreateElement("New_Node");
        parent_xNode.AppendChild(new_xElement);
    }

}

您将新节点添加到XmlDocument并忘记树视图。 TreeView仅显示您的数据。