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.
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"/>
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" />
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With