Search code examples
c#wpfdrag-and-droptextbox

WPF TextBox: Cancelling drop operation leaves Insertion marker


I have a WPF App in that I want to cancel a drop operation to a TextBox, if some conditions are met (see shouldCancelDrop below):

Sample:

XAML:

   <TextBox PreviewDrop="TextBox_PreviewDrop" />

Code behind:

    private void TextBox_PreviewDrop(object sender, DragEventArgs e)
    {
        //Decision if to cancel to drop
        var shouldCancelDrop = false;
        //if (...) shouldCancelDrop = true;
        
        if (shouldCancelDrop)
        {
            e.Handled = true;
            return;
        }

        //...
    }

Problem is: After leaving the TextBox_PreviewDrop-Handler with e.Handled = true the "insertion marker" is always left in the textbox. It looks like a textcursor but is light gray and not blinking, see here (the right black one is the textcursor):

Insertion marker.

How can I get rid of this Insertion marker when I cancel the drop?

It stays in the TextBox until I finish another drag operation!

So I am looking for some "CancelDropOperationAndRedrawTextBox"-Action...


Solution

  • You can use the "PreviewDragOver" event to disallow dropping the element via DragDropEffects.None:

    private void TextBox_OnPreviewDragOver(object sender, DragEventArgs e)
    {
      //Decision if to cancel to drop
      var shouldCancelDrop = false;
      //if (...) shouldCancelDrop = true;
    
      if (shouldCancelDrop)
      {
        e.Effects = DragDropEffects.None;
        return;
      }
    
      //...    
    }