如何强制图像控件关闭它在wpf中打开的文件

use*_*110 4 c# wpf caliburn.micro

我在我的wpf页面上有一个图像,它打开一个图像文件形式的硬盘.用于定义图像的XAML是:

  <Image  Canvas.Left="65" Canvas.Top="5" Width="510" Height="255" Source="{Binding Path=ImageFileName}"  />
Run Code Online (Sandbox Code Playgroud)

我正在使用Caliburn Micro,ImageFileName更新为图像控件应显示的文件名.

当图像通过图像控制打开时,我需要更改文件.但该文件被图像控制锁定,我无法删除或复制任何图像.如何在打开文件或我需要在文件上复制另一个文件时强制图像关闭文件?

我检查过,没有CashOptio图像所以我不能使用它.

Cle*_*ens 9

你可以使用像下面这样的绑定转换器,通过设置BitmapCacheOption.OnLoad将图像直接加载到内存缓存.文件立即加载,之后不锁定.

<Image Source="{Binding ...,
                Converter={StaticResource local:StringToImageConverter}}"/>
Run Code Online (Sandbox Code Playgroud)

转换器:

public class StringToImageConverter : IValueConverter
{
    public object Convert(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        object result = null;
        var path = value as string;

        if (!string.IsNullOrEmpty(uri))
        {
            var image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = new Uri(path);
            image.EndInit();
            result = image;
        }

        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
Run Code Online (Sandbox Code Playgroud)