C#/ WPF:拖放图像

Jie*_*eng 3 c# wpf

我想允许在应用程序中放置图像文件:用户可以将图像从Windows拖放到我的窗口中。我有以下代码,但似乎无法正常工作。我都尝试了FileDropBitmap,都失败了

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

如何检查用户尝试删除的格式?

Isa*_*avo 5

如果用户正在从资源管理器中拖动,那么您所获得的只是文件名列表(带有路径)。一个简单且最有效的解决方案是查看文件扩展名以及它们是否与支持的扩展名预定义列表匹配。

这样的东西(未经测试,甚至可能无法编译,但希望您能理解)

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;
Run Code Online (Sandbox Code Playgroud)