C# DragDrop object with children results in System.InvalidOperationException
I have implemented Drag and Drop on a treeview in WPF, which works as intended. However, it is only adding the root element (the one dragged over) to the data object holding the values of the tree, but adding all of the children (and their children, and so on) to the visual tree.
Here is my first attempt at adding the children to the data object (this should add the first sub-level):
public void DropNewProjectOrganLocation(OrganLocationViewModel organLocation)
{
_projOrganLocation.Add(organLocation);
ObservableCollection<OrganLocationViewModel> subOrgans = organLocation.SubOrganLocations;
foreach (OrganLocationViewModel node in subOrgans)
{
organLocation.SubOrganLocations.Add(node);
node.ParentOrganLocation = organLocation;
}
}
Now when I drag and drop an item that has no children, it works as intended (and is added to the object tree as well as the visual tree). However, when I try to drag and drop an item that has any number of children, it loops through the foreach
code block, then when it finishes and tries to complete the dragdrop, it errors out with this error message:
An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationCore.dll
Additional information: Collection was modified; enumeration operation may not execute
and I'm using the DoDragDrop
method from System.Windows.DragDrop
Here is the line that causes the error:
System.Windows.DragDrop.DoDragDrop(m_DragInfo.VisualSource, data, m_DragInfo.Effects);
Does anyone know how I can recursively add children nodes to th开发者_如何学编程e object tree?
As the exception message suggests, the problem is that you are enumerating and modifying the same collection at the same time, which is not allowed:
ObservableCollection<OrganLocationViewModel> subOrgans = organLocation.SubOrganLocations;
foreach (OrganLocationViewModel node in subOrgans)
{
organLocation.SubOrganLocations.Add(node);
node.ParentOrganLocation = organLocation;
}
Here you enumerate organLocation.SubOrganLocations
and inside the foreach
operator adding items to it. And this behavior is probably not what you want either.
精彩评论