Drag and drop files into WPF

Eamonn McEvoy picture Eamonn McEvoy · Apr 14, 2011 · Viewed 74.6k times · Source

I need to drop an image file into my WPF application. I currently have a event firing when I drop the files in, but I don't know how what to do next. How do I get the Image? Is the sender object the image or the control?

private void ImagePanel_Drop(object sender, DragEventArgs e)
{
    //what next, dont know how to get the image object, can I get the file path here?
}

Answer

A.R. picture A.R. · Apr 14, 2011

This is basically what you want to do.

private void ImagePanel_Drop(object sender, DragEventArgs e)
{

  if (e.Data.GetDataPresent(DataFormats.FileDrop))
  {
    // Note that you can have more than one file.
    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

    // Assuming you have one file that you care about, pass it off to whatever
    // handling code you have defined.
    HandleFileOpen(files[0]);
  }
}

Also, don't forget to actually hook up the event in XAML, as well as setting the AllowDrop attribute.

<StackPanel Name="ImagePanel" Drop="ImagePanel_Drop" AllowDrop="true">
    ...
</StackPanel>