简体   繁体   中英

Dragging and Dropping in WPF

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?

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

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