开发者

WPF - adding a node to a treeview and saving it as XML

I have the following code to open an XML file and bind it to a TreeView, but how do I add a child node or parent node to the selected node? Thank you.

<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="AliceB开发者_运维技巧lue"
              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 event:

            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;
            }


Something like this:

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);
    }

}

You add new node to your XmlDocument and forget about treeview. TreeView only shows your data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜