WPF Image element locks my local file

21 篇文章 0 订阅

WPF Image element locks my local file

    When using the Image element and specifying a local resource Uri in the Source attribute that resource will be locked by your application's process.

<Image Source="C:\Image\Josh.png" />

The file can't be deleted or modified whilst it's locked and this can be a problem if the image was generated and the application wants to clean it up when the user has finished looking at it. There is a simple work around for this, specifying the BitmapImage directly and specifying the CacheOption as OnLoad:

<Image>
    <Image.Source>
        <BitmapImage UriSource="C:\Image\Josh.png" CacheOption="OnLoad" />
    </Image.Source>
</Image>

But

However, there is one big problem with this. The UriSource doesn't work with a binding, e.g.:

<Image>
    <Image.Source>
        <BitmapImage UriSource="{Binding MyImageUrl}" CacheOption="OnLoad" />
    </Image.Source>
</Image>

The good news is, there's another workaround for this by implementing an IValueConverter that returns a BitmapImage with the CacheOption set to OnLoad.

public class UriToCachedImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return null;

        if (!string.IsNullOrEmpty(value.ToString()))
        {
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri(value.ToString());
            bi.CacheOption = BitmapCacheOption.OnLoad;
            bi.EndInit();
            return bi;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException("Two way conversion is not supported.");
    }
}

Now we can go back to using the Image tag alone, and use our new converter to return a cached BitmapImage:

<Image Source="{Binding MyImageUrl, Converter={StaticResource uriToImageConv}}"/>

... where uriToImageConv is the key of a static resource of type UriToCachedImageConverter.

this article comes from http://thejoyofcode.com/WPF_Image_element_locks_my_local_file.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值