删除窗口的背景图片WPF [英] Deleting a window's background image WPF

查看:82
本文介绍了删除窗口的背景图片WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WPF中遇到一个问题,即在应用程序的另一部分尝试写入图像之前,窗口在关闭后没有释放它在背景图像文件上的文件锁.

I'm having a problem in WPF where a window doesn't release it's file-lock on the background image file after closing, before another part of the application tries to write to the image.

举个例子;说我有一个WPF应用,该应用包含3个窗口,1个菜单"选择窗口和2个其他窗口.这两个窗口都使用 BitmapImage 作为 ImageSource (相同图像)来创建 ImageBrush .

So as an example; say I have a WPF app consisting of 3 windows, 1 "menu" selection window and 2 others. Both of the windows create an ImageBrush using a BitmapImage as the ImageSource (the same image).

窗口A具有一个按钮,当按下该按钮时,通过将可用的背景图像复制到用作原始 ImageSource 的文件上并创建新的 ImageBrush 来循环显示可用的背景图像,然后将 Window.Background 设置为新的画笔.

Window A has a button that when pressed, cycles through the available background images by copying them each over the file used as the original ImageSource and creating a new ImageBrush and setting the Window.Background to the new brush.

窗口B仅使用 ImageBrush 绘制 Window.Background .

如果启动了窗口A,切换了背景,关闭了窗口,然后启动了窗口B,则一切正常.

If Window A is launched, backgrounds switched, closed and then Window B launched, everything is fine.

如果启动并关闭了窗口B,则将启动窗口A,并且切换背景的窗口崩溃.尝试切换背景会引发 IOException ,因为:

If Window B is launched, closed, then Window A is launched and backgrounds switched it crashes. Trying to switch the backgrounds throws an IOException because:

该进程无法访问文件'C:\ Backgrounds \ Background.png',因为它正在被另一个进程使用."

"The process cannot access the file 'C:\Backgrounds\Background.png' because it is being used by another process."

因此,窗口B必须仍然以某种方式保持住它!?我试过做一个 GC.Collect();GC.WaitForPendingFinalizers(); 看看是否可以解决问题,但不能解决.

So Window B must still be holding onto it somehow!? I have tried doing a GC.Collect(); GC.WaitForPendingFinalizers(); to see if that cures the problem but it doesn't.

推荐答案

Thomas给出的答案是正确的,并且如果您有文件路径,不想缓存位图并且不想使用它,效果很好.XAML.

The answer Thomas gave is correct, and works well if you have a file path, don't want to cache the bitmap, and don't want to use XAML.

不过,还应该提到BitmapImage具有通过设置BitmapCacheOption立即加载位图的内置方式:

However it should also be mentioned that BitmapImage has a built-in way to load the bitmap immediately by setting BitmapCacheOption:

BitmapImage img = new BitmapImage { CacheOption = BitmapCacheOption.OnLoad };
img.BeginInit();
img.UriSource = imageUrl;
img.EndInit();

<BitmapImage CacheOption="OnLoad" UriSource="..." />

这将立即加载位图并显式关闭流,就像使用FileStream一样,但有一些区别:

This will load the bitmap immediately and explicitly close the stream, just as using a FileStream would, but with several differences:

  • 它可以与任何Uri一起使用,例如pack://Uri.
  • 可以直接在XAML中使用
  • 位图被缓存在位图缓存中,因此将来使用同一Uri不会进入磁盘.在您的特定应用中,这可能是一件坏事,但对于其他用途,则可能是理想的功能.

这篇关于删除窗口的背景图片WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆