Reputation: 1402
I am trying to implement drag and drop functionality in my WPF application. I have a Listbox that I would like to be able to drop files on from Windows Explorer. These files would then be added to the listbox. I had this working at one time, following this tutorial: Drag and drop files to WPF application and asynchronously upload to ASP.NET Web API. Minus the upload to web api part. I just want to show the files in my listbox.
The problem is that the DragOver event never fires. What am I missing? I had this working earlier, but some small tweak messed it up.
Here is my XAML (simplified the parent elements):
<Window>
<Grid>
<TabControl>
<TabItem>
<Grid>
<GroupBox>
<ListBox Name="lstTarget" AllowDrop="True"
Drop="lstTarget_Drop"
DragOver="lstTarget_DragOver"
DragLeave="lstTarget_DragLeave"
BorderThickness="3"
BorderBrush="Red"
>
</ListBox>
Here is my code behind
private void lstTarget_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string filePath in files)
{
lstTarget.Items.Add(filePath);
}
}
var listbox = sender as ListBox;
listbox.Background = new SolidColorBrush(Color.FromRgb(226, 226, 226));
}
private void lstTarget_DragOver(object sender, DragEventArgs e)
{
lstTarget.BorderBrush = Brushes.Green;
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effects = DragDropEffects.Copy;
var listbox = sender as ListBox;
listbox.Background = new SolidColorBrush(Color.FromRgb(155, 155, 155)
}
else
{
e.Effects = DragDropEffects.None;
}
}
private void lstTarget_DragLeave(object sender, DragEventArgs e)
{
var listbox = sender as ListBox;
listbox.Background = new SolidColorBrush(Color.FromRgb(226, 226, 226));
}
Upvotes: 2
Views: 2581
Reputation: 476
I am not sure the problem is that, but I would rather use DragEnter instead of DragOver, as you need to check the dragged data content just once
Upvotes: 1
Reputation: 1402
Well I'm a dummy. If I run my app as Administrator, then I can't drag in items from Explorer. Most likely they are running in a different security context.
There was nothing wrong with my code.
Upvotes: 9