Search code examples
c#wpfxamlio

How to break a binding so you can delete an asset


I have an .jpg file that is bound to an image element like so:

<Image Source="{Binding FileName}"/>

I am allowing the user to delete a folder with all of it's contents, and the contents include this image. When they delete it, the image is removed from the interface as the listview is updated. The object deletes in memory just fine, however the deletion of the assets on the hard drive fails due to an access violation because the image is already in use. I have tried to break the binding of this image before I delete it by setting the value to null, but I still get the violation:

selectedLayout.FileName = null;
var dir = new DirectoryInfo("c:\\myFolder");
dir.Delete(true); // true tells it to delete recursivly

So my question is, how can I "unbind" the .jpg file from the property FileName in my xaml page so that I can delete the file from my hard drive and shake this access exception?


Solution

  • Instead of binding to a string, you could bind to a BitmapImage with CacheOption as BitmapCacheOption.OnLoad.

    Change the type of your FileName source property to BitmapImage and set it like this:

    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.UriSource = new Uri(@"D:\pic.png");
    image.EndInit();
    
    FileName = image;
    

    You should then be able to delete D:\pic.png while still running your application.