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