WPF – Reference an Image without a file lock

I had a situation where I needed the user to select an image to display and then move the location of the image. What I quickly found was while I was bound to the image I was holding a file lock on it that prevented me from moving it.  On a BitmapImage there is a CacheOption that allows you to cache OnLoad. Unfortunately I couldn’t set this on the bindings for the Image so to get around it I had to use a converter on the 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.");
    }
} 

<Image Source="{Binding Path=SmallThumbnailImageLocation, 
Converter={StaticResource imagePathConverter}}"/>

Technorati Tags: ,,