简体   繁体   中英

Drag drop in WPF

I have WPF application with drag-n- drop inmplementation... Whenever I drag tree item on a Grid it is processed by DragDrop Event of that Grid , but every time it get fired twice what could be the reason?

Below is code for implementing drag drop on a TreeView :

 void treeViewGroups_MouseMove(object sender, MouseEventArgs e)
 {
   try
   {
     if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
     {
        Point position = e.GetPosition(null);
        if (Math.Abs(position.X - this.startPoint.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(position.Y - this.startPoint.Y) > SystemParameters.MinimumVerticalDragDistance)
        {
          DataRowView treeViewItem = this.treeViewGroups.SelectedItem as DataRowView;
          if (treeViewItem != null)
          if ((treeViewItem.Row.Table.TableName == "TableGroup"))
          {
             ViewTaxSCConstants.dragElement = treeViewItem;
             Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, new System.Threading.ParameterizedThreadStart(DoDragDrop), treeViewItem);                                
           }
        }
     }
}

I had nearly the same problem: I started the drag event on MouseMove and had a drop event on certain TreeViewItems. After the drop event fired first, it'd fire a second time but the target would be a different element (in my case, the parent of the one that was my target).

To solve it, I had to set e.Handled = true in the Drop event.

I think this is a good method for Drag & Drop

A good way for darg and drop are explained as

Detect a drag as a combinatination of MouseMove and MouseLeftButtonDown

Find the data you want to drag and create a DataObject that contains the format, the data and the allowed effects.

Initiate the dragging by calling DoDragDrop()

Set the AllowDrop property to True on the elements you want to allow dropping.

Register a handler to the DragEnter event to detect a dragging over the drop location. Check the format and the data by calling GetDataPresent() on the event args. If the data can be dropped, set the Effect property on the event args to display the appropriate mouse cursor.

When the user releases the mouse button the DragDrop event is called. Get the data by calling the GetData() method on the Data object provided in the event args.

You can find the complete article here

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