简体   繁体   中英

Cant' delete SelectedItem from TreeView binded to XML

I'm binded my TreeView ItemsSource to XmlDocument via XmlDataProvider.

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>

code behind:

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

When I edit some info inside my tree or add new nodes, I can easily save data and refresh the tree. But when I try to delete the branch with this function

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

I get an error: Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead. Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.

So, how to make it properly remove items from tree and from XmlDocument? Thanks in advance.

Oh, did not know that Items collection of TreeView contains objects of the binded type. Getting those objects as XmlElement made removal pretty easy operation. Just deleted SelectedItem from Provider.Document .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM