Cannot delete file when used in DataContext

The problem is not the DataContext, but simply the way WPF loads images from files.

When you bind the Source property of an Image control to a string that contains a file path, WPF internally creates a new BitmapFrame object from the path basically like this:

string path = ...
var bitmapImage = BitmapFrame.Create(new Uri(path));

Unfortunately this keeps the Image file opened by WPF, so that you can’t delete it.

To get around this you have to change the type of your image property to ImageSource (or a derived type) and load the image manually like shown below.

public ImageSource ImageSource { get; set; } // omitted OnPropertyChanged for brevity

private ImageSource LoadImage(string path)
{
    var bitmapImage = new BitmapImage();

    using (var stream = new FileStream(path, FileMode.Open))
    {
        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource = stream;
        bitmapImage.EndInit();
        bitmapImage.Freeze(); // optional
    }

    return bitmapImage;
}

...
ImageSource = LoadImage(@"C:\Users\Dave\Desktop\Duplicate\Swim.JPG");

Leave a Comment