Question

I'm trying to drag an image file from explorer into my wpf image control. My current code is

private void Image_Drop(object sender, DragEventArgs e)
{
    string fpath = (string)e.Data.GetData(DataFormats.StringFormat); 
    BitmapImage tmpImage = new BitmapImage((new Uri(fpath))); 
    testImg.Source = tmpImage;
}

Which is currently giving me NullReferenceException error when I drop the file on the control.

Update:

Using Patrick's suggestion, by changing the code to this

private void Image_Drop(object sender, DragEventArgs e)
{
    object data = e.Data.GetData(DataFormats.FileDrop);

    foreach (string str in (string[])data)
    {
        BitmapImage tmpImage = new BitmapImage((new Uri(str)));
        testImg.Source = tmpImage;
    }
}

The image correctly update the source. Will probably need to add code for handling multiple images selection drop.

Was it helpful?

Solution

You should use the DataFormats.FileDrop. It will give a list of file names in the GetData. This is a working example from my own app:

object data = e.Data.GetData(DataFormats.FileDrop);

if (data is string[])
{
    string[] files = (string[])data;
}

OTHER TIPS

You are trying to get a file as a string, so I imagine it's your e.Data.GetData(DataFormats.StringFormat) line that is throwing. If you're dropping a bitmap onto your control then you can treat it as such. Try this.

private void Image_Drop(object sender, DragEventArgs e)
{
    BitmapImage tmpImage = e.Data.GetData(DataFormats.Bitmap);
    testImg.Source = tmpImage;
}

Although I recommend you put in code to ensure you are checking the type of what has been dragged onto your control before assuming it is a bitmap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top