如何从WPF中的图像源释放图像

我正在加载图像如下

XAML

 

代码隐藏

 if (Path.GetFileNameWithoutExtension(filePath).ToLower().Contains(slugName.ToLower() + "_70x70")) { imgThumbnail.BeginInit(); imgThumbnail.Stretch = Stretch.UniformToFill; imgThumbnail.Source = new BitmapImage(new Uri(filePath)); imgThumbnail.EndInit(); count = count + 1; } 

上面的代码工作正常,现在我的缩略图旁边有一个删除按钮,如果删除按钮,我想删除源位置的所有图像。

这是删除图像文件的代码

 internal int Remove(string slugName, DirectoryInfo outputFolder) { Helper.MetadataView.imgThumbnail.Source = null; foreach (string filePath_ToBeDeleted in filePathList_ToBeDeleted) { if (File.Exists(filePath_ToBeDeleted)) { Helper.MetadataView.imgThumbnail.IsEnabled = false; File.Delete(filePath_ToBeDeleted); count += 1; } } return count; } return 0; // slugName == null } 

我尝试将源为null并删除,但它会抛出exception,如下所示

该进程无法访问文件’\ serv1 \ Dev \ Images \ 730_Test4_0406_70x70.jpg’,因为它正由另一个进程使用。

我不确定如何处置,请有人指导我。

如果要删除或移动它,则不应在应用程序中直接使用该Image

 imgThumbnail.Source = new BitmapImage(new Uri(filePath)); 

相反,这样做:

 BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.UriSource = new Uri(filePath); image.EndInit(); imgThumbnail.Source = image; 

更多阅读本文

为了获得良好的代码重用,可以使用绑定转换器:

 namespace Controls { [ValueConversion(typeof(String), typeof(ImageSource))] public class StringToImageSourceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!(value is string valueString)) { return null; } try { ImageSource image = BitmapFrame.Create(new Uri(valueString), BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad); return image; } catch { return null; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } 

例如,有一个用于绑定的字符串

 public string MyImageString { get; set; } = @"C:\test.jpg" 

在UI中使用了转换器,在我的例子中来自名为“Controls”的库