我当前正在尝试在WPF对话框中显示图像,用户可以随时替换该图像,从而导致此图像文件被覆盖。我的问题是:当图像显示在我的对话框中时,图像似乎被WPF锁定了,所以当我试图替换它时,它无法访问。
如何在上传新镜像时强制WPF释放镜像?以下是我的代码的一部分:
XAML:
<Image Margin="6" VerticalAlignment="Center" HorizontalAlignment="Center" Source="{Binding ImageFileFullPath}"/>C#:
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‘类型的未经处理的异常
发布于 2016-06-06 15:51:48
我遇到过这样一种情况:我需要用户选择要显示的图像,然后移动图像的位置。我很快发现,当我绑定到图像时,我对它进行了文件锁定,阻止了我移动它。在BitmapImage上,有一个允许您缓存OnLoad的CacheOption。不幸的是,我不能在Image的绑定上设置它,所以为了绕过它,我不得不在Source上使用一个转换器:
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:
<Image Source="{Binding Path=SmallThumbnailImageLocation, Converter=StaticResource imagePathConverter}}"/>https://stackoverflow.com/questions/37650812
复制相似问题