在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:UsersDaveDesktopDuplicateSwim.JPG"); try { File.Delete(@"C:UsersDaveDesktopDuplicateSwim.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
(或派生类型)并手动加载图像,如下所示。
上述就是C#学习教程:在DataContext中使用时无法删除文件分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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:UsersDaveDesktopDuplicateSwim.JPG");
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/989111.html