2011-05-14 32 views
0

我有以下代码来打开XML文件并将其绑定到TreeView,但是如何将子节点或父节点添加到选定节点?谢谢。WPF - 将节点添加到树视图并将其保存为XML

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

你可以添加更多的信息!你想用button1.click事件做到这一点?什么问题? – Rev 2011-05-15 07:53:06

+0

我想要做的是将一个子节点添加到节点,或者在所选节点上向它添加一个父节点。 – user646265 2011-05-15 09:09:46

+0

我不会使用XmlDataProvider。相反,我会创建一个clr对象的集合并将它们绑定到treeview。 – vorrtex 2011-05-15 11:01:28

回答

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只显示你的数据。