无法删除按钮使用的图像

时间:2011-07-26 13:05:37

标签: c# wpf image xaml button

我有一个wpf应用程序,它有一个按钮,用于存储用户硬盘上某个路径下的每个文件夹。每个文件夹都包含一个显示在按钮上的图像和一个在单击按钮时运行的文件。这是我用于按钮的模板:

   <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>

绑定值是图像的路径,绑定键是单击按钮时运行的另一个文件的路径。问题是DeleteMenuItem函数。我想删除包含图像的文件夹,但它不会让我,因为按钮正在使用图像文件。如何释放我的应用程序使用的图像,以便我可以安全地删除该文件夹?

1 个答案:

答案 0 :(得分:4)

默认情况下,BitmapImage的BitmapCacheOptionOnDemand,您可以通过拥有自己的OnLoad将其更改为ValueConverter,这样可以解决您的问题。

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}}"/>