Cannot delete image used by button

I have a wpf application that has a button for each folder under a specific path on the user's hard drive. Each folder contains an image that is displayed on the button and a file that is launched when the button is pressed. Here is the template I use for the button:

<DataTemplate x:Key="ProgramItemDataTemplate"> <Button Style="{StaticResource ButtonStyle}" Click="Program_Click" Tag="{Binding Key}"> <Button.ContextMenu> <ContextMenu> <MenuItem x:Name="DeleteMenuItem" Click="DeleteMenuItem_Click" Header="Delete" Tag="{Binding Key}" /> </ContextMenu> </Button.ContextMenu> <StackPanel> <Image Source="{Binding Value}" MaxWidth="200" MaxHeight="175"></Image> <TextBlock Text="{Binding Key,Converter={StaticResource PathToNameConverter2}}" TextWrapping="Wrap" TextAlignment="Center" /> </StackPanel> </Button> </DataTemplate> 

The binding value is the path to the image, and the binding key is the path to another file that is launched when the button is clicked. The problem is the DeleteMenuItem function. I want to delete the folder containing the image, but this will not allow me, because the image file is used by the button. How can I free the image from use by my application so that I can safely delete the folder?

+4
source share
1 answer

By default, BitmapImage BitmapCacheOption is OnDemand , you can change this to OnLoad with your own ValueConverter , and this should solve your problem.

 public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.UriSource = new Uri(value.ToString()); image.EndInit(); return image; } <Image Source="{Binding Path, Converter={StaticResource ImageConverter}}"/> 
+4
source

All Articles