【问题标题】:How to break a binding so you can delete an asset如何打破绑定以便删除资产
【发布时间】:2019-02-28 14:56:45
【问题描述】:

我有一个绑定到图像元素的 .jpg 文件,如下所示:

<Image Source="{Binding FileName}"/>

我允许用户删除包含所有内容的文件夹,并且内容包括此图像。当他们删除它时,随着列表视图的更新,图像将从界面中删除。该对象在内存中删除得很好,但是由于访问冲突,硬盘驱动器上的资产的删除失败,因为该图像已在使用中。我试图通过将值设置为 null 来破坏此图像的绑定,然后将其删除,但我仍然得到违规:

selectedLayout.FileName = null;
var dir = new DirectoryInfo("c:\\myFolder");
dir.Delete(true); // true tells it to delete recursivly

所以我的问题是,如何从我的 xaml 页面中的属性 FileName 中“取消绑定” .jpg 文件,以便我可以从硬盘驱动器中删除该文件并消除此访问异常?

【问题讨论】:

    标签: c# wpf xaml io


    【解决方案1】:

    您可以将CacheOption 绑定到BitmapImage,而不是绑定到string,作为BitmapCacheOption.OnLoad

    FileName 源属性的类型更改为 BitmapImage 并设置如下:

    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.UriSource = new Uri(@"D:\pic.png");
    image.EndInit();
    
    FileName = image;
    

    然后您应该能够在仍然运行您的应用程序的同时删除D:\pic.png

    【讨论】:

    • 完美!神圣的 Shiza - 我真的不认为这会奏效。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2011-12-24
    • 2014-11-02
    • 2013-08-18
    相关资源
    最近更新 更多