Reputation: 4897
I've got a TreeView
and Canvas
in my WPF application. I'm trying to implement functionality whereby users can drag a TreeViewItem and a method should be called when the user drops on the canvas, passing the TreeViewItem header as a parameter to this method.
This is what I've done so far:
private void TreeViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.Source.GetType().Name.Equals("TreeViewItem"))
{
TreeViewItem item = (TreeViewItem)e.Source;
if (item != null)
{
DataObject dataObject = new DataObject();
dataObject.SetData(DataFormats.StringFormat, item.Header.ToString());
DragDrop.DoDragDrop(item, dataObject, DragDropEffects.Copy);
}
}
}
When I drag and drop to the canvas nothing happens. I am thus unsure of what I should do next. I feel that it's something really small, but I'm at a loss. How can I call the method and detect that the header has been dropped?
Any ideas?
Upvotes: 6
Views: 20820
Reputation: 45135
You need to set AllowDrop
to true on your target element and then handle DragOver
and Drop
events on the target element.
Example:
private void myElement_DragOver(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent(typeof(MyDataType)))
{
e.Effects = DragDropEffects.None;
e.Handled = true;
}
}
private void myElement_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(MyDataType)))
{
// do whatever you want do with the dropped element
MyDataType droppedThingie = e.Data.GetData(typeof(MyDataType)) as MyDataType;
}
}
Upvotes: 8