Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropping a file in a WPF TextBox

I have found this question MANY times on Google and Stack Overflow. None of the solutions work.

I have a TextBox. AllowDrop is set to true. I first tried DragEnter/DragOver/Drop events and then switched to "Preview" events for all of these. No event EVER gets called no matter what I do. Next I tried adding handlers after InitializeComponent(). No luck.

Xaml - commented out because I can't post it otherwise:

<TextBox PreviewDragEnter="OutputFolder_DragEnter" PreviewDragOver="OutputFolder_DragOver" AllowDrop="True" PreviewDrop="OutputFolder_Drop" />

No C# code posted because no breakpoint is ever hit. It simply doesn't work. As I mentioned, I did try adding a handler manually but still can't get it working.

like image 390
Paul Avatar asked Jul 30 '14 17:07

Paul


3 Answers

Subscribe the PreviewDragHandler and set e.Handled = true. Then Drop event should fire.

    private void TextBox_PreviewDragOver(object sender, DragEventArgs e)
    {
        e.Handled = true;
    }

XAML looks like below,

    <TextBox VerticalAlignment="Center" AllowDrop="True" 
PreviewDragOver="TextBox_PreviewDragOver"/>
like image 59
Jawahar Avatar answered Oct 04 '22 23:10

Jawahar


IIRC Drag Events only get raised if the drag started inside the WPF application. What you want is the Drop Event. This Code works fine for me.

C#:

private void ListBox_Drop(object sender, DragEventArgs e)
{
    var fileNames = (string[]) e.Data.GetData(DataFormats.FileDrop);
    if (fileNames == null) return;
    var fileName = fileNames.FirstOrDefault();
    if (fileName == null) return;
    (sender as ListBox).Items.Add(fileName);
}

xaml:

<ListBox AllowDrop="True" Drop="ListBox_Drop" />
like image 28
Marcel B Avatar answered Oct 05 '22 01:10

Marcel B


Are you running Visual Studio as an administrator when this problem happens? Windows/UAC will usually block drag/drop operations from outside the running program if it was launched with elevated privileges (especially if you're on a user account that isn't an administrator for the domain).

This is a problem I commonly run into which can bug for me far too long before I remember to restart Visual Studio as a non-administrator (N.B. this problem applies to both WPF and WinForms projects).

like image 36
Dmihawk Avatar answered Oct 04 '22 23:10

Dmihawk