I have a static (for the moment) tree set up in WPF. I am attempting to delete a specific child out of a parent, which is a sub-item of main, but not sure how to go about it. The tree is structured as :
I have a delete button with a Click event written as so:
private void TreeView_Selected_Delete(object sender, RoutedEventArgs e)
{
MainTestList.Items.Remove(MainTestList.SelectedItem);
}
However, this can only ever delete the "Main" item, or the root/root parent
Just to try, I also attempted using MainTestList.Items.RemoveAt(MainTestList.Items.IndexOf(MainTestList.SelectedItem));
but that does the same, except throwing an exception of
System.ArgumentOutOfRangeException: 'removeIndex is less than zero or greater than or equal to Count. (Parameter 'index')'
My understanding is that the TreeView is an index of items, but any item in that has it's own index, thus the above doesn't work, because the index is wrong for the item in question. So each Item in a TreeView is a Parent if there are any children inside of it (Main is parent to submenu2, which is a parent to submenu2_2, which is a parent to the deepitem child.)
So, how do I get to the specific (deep item) to work with it, without touching any identical children/parents.
I'm guessing it's some sort of matching the MainTestList.SelectedItem against MainTestList 's tree, but I'm not sure exactly how that would go, then somehow form a path to it to work specifically with that deepitem ?
For that case, we would need helper method that will recursively scan TreeView
in order to find item to delete.
Here's implementation:
private bool RemoveChildFromTreeView(ItemCollection parentTreeViewItems, TreeViewItem treeViewItem)
{
if (parentTreeViewItems.Contains(treeViewItem))
{
parentTreeViewItems.Remove(treeViewItem);
return true;
}
foreach (TreeViewItem item in parentTreeViewItems)
{
if (RemoveChildFromTreeView(item.Items, treeViewItem))
return true;
}
return false;
}
And you can invoke it like
RemoveChildFromTreeView(MainTreeView.Items, (TreeViewItem)MainTreeView.SelectedItem);