C#/WPF: Drag & Drop Images
I want to allow dropping of image files in my application: Users can Drag images from Windows and Drop them into my Window. I have the following code but it seems its not working. I tried both FileDrop
& Bitmap
, both fails
private void Border_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.Get开发者_JS百科DataPresent(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 what formats the user is trying to drop?
If the user is dragging from the explorer, then all you get is a list of filenames (with path). A simple and mostly working solution would be to look at the file extensions and if they match a pre-defined list of supported extensions.
Something like this (not tested, may not even compile, but hopefully you get the idea)
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;
精彩评论