将图像文件从资源管理器拖放到应用程序

时间:2014-04-01 15:02:49

标签: passwords

我试图将图像文件从资源管理器拖到我的wpf图像控件中。我目前的代码是

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;
}

当我将文件放在控件上时,当前正在给我NullReferenceException错误。

更新

使用Patrick的建议,将代码更改为

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;
    }
}

图像正确更新源。可能需要添加代码来处理多个图像选择丢弃。

2 个答案:

答案 0 :(得分:2)

您应该使用DataFormats.FileDrop。它将在GetData中提供文件名列表。这是我自己的应用程序中的一个工作示例:

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

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

答案 1 :(得分:1)

您正在尝试将文件作为字符串,因此我认为这是您的e.Data.GetData(DataFormats.StringFormat)行投掷。如果你将一个位图放到你的控件上,你可以这样对待它。试试这个。

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

虽然我建议您输入代码以确保在假设它是位图之前检查已拖动到控件上的内容的类型。