WPF: How to cancel drag & drop on Escape

QueryContinueDrag occurs during a drag-and-drop operation and enables the drag source to determine whether the drag-and-drop operation should be canceled. (MSDN Reference)

The user can attach an event handler to the item being dragged and within the event handler, the user can listen if escape was pressed.

If escape is pressed the user can set e.Action to DragAction.Cancel and the drag & drop operation will be cancelled.

For example:
// Attach QueryContinueDrag event handler before you perform Drag & Drop
_draggedElt.QueryContinueDrag += OnDragSourceQueryContinueDrag; 

// Perform DragDrop
DragDrop.DoDragDrop(_draggedElt, data, DragDropEffects.All);
// Detach QueryContinueDrag event handler after Drag & Drop is complete
_draggedElt.QueryContinueDrag -= OnDragSourceQueryContinueDrag;
          
private static void OnDragSourceQueryContinueDrag(object sender, QueryContinueDragEventArgs e)
        {
            if (e.EscapePressed)
            {
                e.Action = DragAction.Cancel;
            }
            // Make sure you don't set e.Handled to true
            // e.Handled = true;
        }

Comments

Popular posts from this blog

WPF How to Dispose ViewModel when the associated UserControl (Not Window) closes?

C# How to unit test Dispatcher

WPF: How to Deep Copy WPF object (e.g. UIElement) ?