在DataContext中使用时无法删除文件

我的应用程序在屏幕上显示图像(基于本地计算机上的文件的图像),用户可以根据需要删除它们。

每次我尝试删除文件时,都会导致以下错误消息:

"The process cannot access the file 'C:\\Users\\Dave\\Desktop\\Duplicate\\Swim.JPG' because it is being used by another process." 

我理解错误信息。

我有一个UserControl接受文件路径(通过构造函数中的参数),然后将其绑定到它的(UserControl) DataContext

作为调试此问题的一部分,我发现问题是由于在UserControl中设置DataContext。 如果我删除this.DataContext = this; 从我的UserControl中,然后我可以删除该文件。

所以,我的TestUnit看起来像

  Ui.UserControls.ImageControl ic = new ImageControl( @"C:\Users\Dave\Desktop\Duplicate\Swim.JPG"); try { File.Delete(@"C:\Users\Dave\Desktop\Duplicate\Swim.JPG"); } catch (Exception ex) { Assert.Fail(ex.Message); } 

UserControl CodeBehind

  public ImageControl(string path) { this.FilePath = path; this.DataContext = this; // removing this line allows me to delete the file! InitializeComponent(); } #region Properties private string _filePath; public string FilePath { get { return _filePath; } set { _filePath = value; OnPropertyChanged("FilePath"); } } 

如果重要,我的UserControl XAML正在使用’Image’控件,绑定到’FilePath’

我尝试在删除之前使UserControl为null,这没有帮助。

我已经尝试将IDisposible接口添加到我的UserControl并在Dispose()方法设置this.DataContext = null; 但这没有帮助。

我究竟做错了什么? 如何删除此文件(或更准确地说,将其取消使用)。

问题不在于DataContext,而在于WPF从文件加载图像的方式。

当您将Image控件的Source属性绑定到包含文件路径的字符串时,WPF会在内部从路径创建一个新的BitmapFrame对象,基本上如下所示:

 string path = ... var bitmapImage = BitmapFrame.Create(new Uri(path)); 

不幸的是,这会使WPF打开Image文件,因此您无法删除它。

要解决此问题,您必须将图像属性的类型更改为ImageSource (或派生类型)并手动加载图像,如下所示。

 public ImageSource ImageSource { get; set; } // omitted OnPropertyChanged for brevity private ImageSource LoadImage(string path) { var bitmapImage = new BitmapImage(); using (var stream = new FileStream(path, FileMode.Open)) { bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.StreamSource = stream; bitmapImage.EndInit(); bitmapImage.Freeze(); // optional } return bitmapImage; } ... ImageSource = LoadImage(@"C:\Users\Dave\Desktop\Duplicate\Swim.JPG");