问题
I have a drag and drop from a ListBox into a TreeView, the problem I have is that I can only see the "IsSelected" node that is returned from the TreeView sender under the Drop event, this is because I am selecting a property from the listbox of a TreeViewItem and dragging it into another TreeViewItem.
I hope that makes sense.
I can't get the data from the "dropped" TreeViewItem, I currently have these methods but I can't get the TreeViewItem I drop the ListBoxItem into.
private void nodeTree_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("copyProperty"))
{
BasePropertyTypeVM dragged = e.Data.GetData("copyProperty") as BasePropertyTypeVM;
}
}
private void NodeTree_OnDragEnter(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent("copyProperty") ||
sender == e.Source)
{
e.Effects = DragDropEffects.None;
}
}
private void NodeTree_OnDragOver(object sender, DragEventArgs e)
{
TreeViewItem treeViewItem = FindAncestor<TreeViewItem>((DependencyObject) e.OriginalSource);
if (treeViewItem != null)
{
treeViewItem.Background = Brushes.Blue;
}
}
private void NodeTree_OnDragLeave(object sender, DragEventArgs e)
{
TreeViewItem treeViewItem = FindAncestor<TreeViewItem>((DependencyObject) e.OriginalSource);
if (treeViewItem != null)
{
treeViewItem.Background = Brushes.White;
}
}
回答1:
So I managed to do this. I used the find ancestor method to get the treeviewitem object and then used the header from this object and converted this to the NodeTreeVM object I had used to create the tree view.
private void nodeTree_Drop(object sender, DragEventArgs e)
{
//find the ancestor using the below method, this gets the TreeViewItem Object
TreeViewItem treeViewItem = FindAncestor<TreeViewItem>((DependencyObject)e.OriginalSource);
if (treeViewItem != null)
{
treeViewItem.Background = Brushes.White;
//Convert the header into the origional object
var droppedNode = (TreeNodeVM)treeViewItem.Header;
}
}
private static T FindAncestor<T>(DependencyObject current) where T : DependencyObject
{
// Search the VisualTree for specified type
while (current != null)
{
if (current is T)
{
return (T) current;
}
current = VisualTreeHelper.GetParent(current);
}
return null;
}
I hope this also helps someone else, please comment for more info :)
来源:https://stackoverflow.com/questions/28460343/getting-a-treeviewitem-from-the-drop-event-in-a-treeview-when-a-different-node-i