如何在WPF (C#)中清除图像控件

4

我有一个图像控件,源图像位于我的C驱动器中。每当我尝试删除原始图像以动态更改为另一张图像时,就会收到消息说该图像正在被另一个进程使用。如何释放图像控件中的图像以便能够删除它。

我尝试了以下变体:

string path = ((BitmapImage)img.Source).UriSource.LocalPath;
img.SetValue(System.Windows.Controls.Image.SourceProperty, null);
File.Delete(path);

同时:

string path = ((BitmapImage)img.Source).UriSource.LocalPath;
img.Source = null;
File.Delete(path)

但是它不起作用...


转帖?http://www.codeproject.com/Questions/391943/Delete-images-in-WPF - mafu
2个回答

1

2Kevin:有趣的方法,但在这种情况下我需要在File.Delete之前使用fs.Close()。这不是很方便。还有其他选项吗? - antongladchenko
我看到的另一个选项是将图像复制到临时目录并打开临时文件。 - kemiller2002
我看到其他帖子,似乎文件在控件释放图像后仍然被锁定,原因未知。 - kemiller2002

-1

//这个函数允许你从文件中加载图像并释放它

 BitmapImage loadPhoto(string path)
    {
        BitmapImage bmi = new BitmapImage();
        bmi.BeginInit();
        bmi.CacheOption = BitmapCacheOption.OnLoad;
        bmi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;            
        bmi.UriSource = new Uri(path);
        bmi.EndInit();
        return bmi;
    }

1
请在您的答案中添加一些描述。https://stackoverflow.com/help/how-to-answer - Angel F Syrus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接