How to force Image control to close the file that

2019-02-26 00:44发布

I have an image on my wpf page which opens an image file form hard disk. The XAML for defining the image is:

  <Image  Canvas.Left="65" Canvas.Top="5" Width="510" Height="255" Source="{Binding Path=ImageFileName}"  />

I am using Caliburn Micro and ImageFileName is updated with the name of file that image control should show.

When the image is opend by image control, I need to change the file. But the file is locked by image control and I can not delete or copy any mage over it. How can I force Image to close the file after it opened it or when I need to copy another file over it?

I checked and there is no CashOptio for image so I can not use it.

1条回答
可以哭但决不认输i
2楼-- · 2019-02-26 01:21

You could use a binding converter like below that loads an image directly to memory cache by setting BitmapCacheOption.OnLoad. The file is loaded immediately and not locked afterwards.

<Image Source="{Binding ...,
                Converter={StaticResource local:StringToImageConverter}}"/>

The converter:

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

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

        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
查看更多
登录 后发表回答