首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF数据绑定到图像文件将永久锁定该文件

WPF数据绑定到图像文件将永久锁定该文件
EN

Stack Overflow用户
提问于 2016-06-06 14:27:13
回答 1查看 334关注 0票数 2

我当前正在尝试在WPF对话框中显示图像,用户可以随时替换该图像,从而导致此图像文件被覆盖。我的问题是:当图像显示在我的对话框中时,图像似乎被WPF锁定了,所以当我试图替换它时,它无法访问。

如何在上传新镜像时强制WPF释放镜像?以下是我的代码的一部分:

XAML:

代码语言:javascript
复制
<Image Margin="6" VerticalAlignment="Center" HorizontalAlignment="Center" Source="{Binding ImageFileFullPath}"/>

C#:

代码语言:javascript
复制
string sourceFile = openFileDialog.FileName;
string destinationFile = Path.Combine(Environment.ExpandEnvironmentVariables(Constants.ImagePathConstant), destinationFileWithoutPath);
mViewModel.ImageFileFullPath = ""; //temporarily set the image file to another entry hoping WPF releases my image
try
{
    File.Copy(sourceFile, destinationFile, true); //fails the second time with exception 
}
catch (Exception)
{                   
    throw;
}

即使尝试将图像临时设置为空路径,也无法解决问题。

Exception I get: PresentationFramework.dll中发生'System.IO.IOException‘类型的未经处理的异常

EN

回答 1

Stack Overflow用户

发布于 2016-06-06 15:51:48

我遇到过这样一种情况:我需要用户选择要显示的图像,然后移动图像的位置。我很快发现,当我绑定到图像时,我对它进行了文件锁定,阻止了我移动它。在BitmapImage上,有一个允许您缓存OnLoad的CacheOption。不幸的是,我不能在Image的绑定上设置它,所以为了绕过它,我不得不在Source上使用一个转换器:

代码语言:javascript
复制
public class ImageCacheConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {

        var path = (string)value;
        // load the image, specify CacheOption so the file is not locked
        var image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.UriSource = new Uri(path);
        image.EndInit();

        return image;

    }

    public object ConvertBack(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException("Not implemented.");
    }
} 

XAML:

代码语言:javascript
复制
<Image Source="{Binding Path=SmallThumbnailImageLocation, Converter=StaticResource imagePathConverter}}"/>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37650812

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档