我的应用程序在屏幕上显示图像(基于本地计算机上文件的图像),用户可以根据需要将其删除。
每次我尝试删除文件时,都会导致以下错误消息:
"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代码
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使用的是绑定到“ FilePath”的“图片”控件
我试图删除之前删除UserControl为null,这没有帮助。
我尝试将IDisposible接口添加到我的UserControl以及Dispose()
方法设置内,this.DataContext = null;
但这没有帮助。
我究竟做错了什么?如何删除此文件(或更准确地说,使其不使用)。
问题不在于DataContext,而仅仅是WPF从文件加载图像的方式。
当您将Source
Image控件的属性绑定到包含文件路径的字符串时,WPF会从该路径内部基本创建一个新的BitmapFrame对象,如下所示:
string path = ...
var bitmapImage = BitmapFrame.Create(new Uri(path));
不幸的是,这会使Image文件由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");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句