Wpf: Drag And Drop To A Textbox Wpf: Drag And Drop To A Textbox wpf wpf

Wpf: Drag And Drop To A Textbox


If you add a handler for PreviewDragOver, then set e.Handled = true it should work.

Works for me in any case.


TextBox seems to have already some default handling for DragAndDrop. If your data object is a String, it simply works. Other types are not handled and you get the Forbidden mouse effect and your Drop handler is never called.

It seems like you can enable your own handling with e.Handled to true in a PreviewDragOver event handler.

I could not find any details about that at MSDN, butfound http://www.codeproject.com/Articles/42696/Textbox-Drag-Drop-in-WPF very helpfull.


You may also want to handle PreviewDragEnter the same way as PreviewDragOver or it will default to the Forbidden Mouse on the first pixel.

In the handler make sure the DragEventArgs.Data is the type you want to drop. If it is, set DragEventsArgs.Effects to DragDropEffects.Move or something else in AllowedEffects. If it isn't the type you want to drop, set to DragDropEffects.None which disables dropping.

XAML for MVVM Light:

<i:Interaction.Triggers>        <i:EventTrigger EventName="Drop">            <cmd:EventToCommand Command="{Binding DragDropCommand}" PassEventArgsToCommand="True" />        </i:EventTrigger>        <i:EventTrigger EventName="PreviewDragOver">            <cmd:EventToCommand Command="{Binding PreviewDragEnterCommand}" PassEventArgsToCommand="True" />        </i:EventTrigger>        <i:EventTrigger EventName="PreviewDragEnter">            <cmd:EventToCommand Command="{Binding PreviewDragEnterCommand}" PassEventArgsToCommand="True" />        </i:EventTrigger>    </i:Interaction.Triggers>

Handler in ViewModel:

        private void ExecutePreviewDragEnterCommand(DragEventArgs drgevent)        {            drgevent.Handled = true;            // Check that the data being dragged is a file            if (drgevent.Data.GetDataPresent(DataFormats.FileDrop))            {                // Get an array with the filenames of the files being dragged                string[] files = (string[])drgevent.Data.GetData(DataFormats.FileDrop);                if ((String.Compare(System.IO.Path.GetExtension(files[0]), ".xls", true) == 0)                    && files.Length == 1)                    drgevent.Effects = DragDropEffects.Move;                else                    drgevent.Effects = DragDropEffects.None;            }            else                drgevent.Effects = DragDropEffects.None;        }