C # / WPF: drag and drop images

I want to allow the deletion of image files in my application: users can drag and drop images from Windows and transfer them to my window. I have the following code, but it seems like it is not working. I tried both FileDrop, and Bitmapboth failed

private void Border_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
        e.Effects = DragDropEffects.Copy;
    } else {
        e.Effects = DragDropEffects.None;
    }
}

private void Border_Drop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        MessageBox.Show(e.Data.GetData(DataFormats.FileDrop).ToString());
    }
    else
    {
        MessageBox.Show("Can only drop images");
    }
}

How can I check which formats the user is trying to delete?

+3
source share
1 answer

If the user drags from the explorer, then all you get is a list of file names (with a path). A simple and mainly working solution would be to look at the file extensions, and if they correspond to a predefined list of supported extensions.

- ( , , , , , )

var validExtensions = new [] { ".png", ".jpg", /* etc */ };
var lst = (IEnumerable<string>) e.Data.GetData(DataFormats.FileDrop);
foreach (var ext in lst.Select((f) => System.IO.Path.GetExtension(f)))
{
    if (!validExtensions.Contains(ext))
        return false;  
}
return true;
+4

Source: https://habr.com/ru/post/1768022/


All Articles