广东话'从TreeView绑定到XML删除SelectedItem

时间:2015-09-22 12:07:32

标签: c# xml wpf data-binding treeview

我通过XmlDataProvider将TreeView ItemsSource绑定到XmlDocument。

XAML:

 <Window.Resources>
    <XmlDataProvider x:Key="XmlData" XPath="/root" />
    <HierarchicalDataTemplate>
        ...
    </HierarchicalDataTemplate>
    ...
 </Window.Resources>
 <GroupBox Header="XMLTree" DataContext="{StaticResource XmlData}">
        <TreeView Name="TemplateTree"
              ItemsSource="{Binding}"
              VirtualizingStackPanel.IsVirtualizing="False"
              VirtualizingStackPanel.VirtualizationMode="Standard" KeyDown="TemplateTree_KeyDown" />
 </GroupBox>
代码背后的代码:

    private void LoadTemplateButton_Click(object sender, RoutedEventArgs e)
    {
            var ofd = new OpenFileDialog();
            ofd.Filter = "XML" + " (*.xml)|*.xml";
            if (ofd.ShowDialog() != true) return;

            Document = new XmlDocument();
            Document.Load(ofd.FileName);
            Provider = (XmlDataProvider) FindResource("XmlData");
            Provider.Document = Document;
            Provider.Source = new Uri(ofd.FileName);
            Provider.Refresh();
    }

当我在树中编辑一些信息或添加新节点时,我可以轻松保存数据并刷新树。但是当我尝试用这个函数删除分支时

    private void TemplateTree_KeyDown(object sender, KeyEventArgs e)
    {
        try
        {
            if (e.Key == Key.Delete)
            {
                TemplateTree.Items.Remove(TemplateTree.SelectedItem);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

我收到错误:Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.

那么,如何正确地从树和XmlDocument中删除项目? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

哦,不知道Items TreeView的集合包含绑定类型的对象。将这些对象作为XmlElement进行移除非常简单。刚刚从SelectedItem删除了Provider.Document