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

查看:235
本文介绍了删除窗口的背景图片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.

因此​​,作为一个例子;说我有包括3个窗口,1菜单选择窗口,2人一个WPF应用程序。同时在Windows中创建一个的ImageBrush 使用的BitmapImage 的ImageSource (中的相同的图片)。

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有一个按钮,当pressed,通过复制他们每个人在作为原始文件的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

Window B simply uses the ImageBrush to draw the 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:\\ \\背景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.

推荐答案

托马斯给出的答案是正确的,效果很好,如果你有一个文件路径,不想缓存的位图,并且不希望使用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:


  • 将与任何开放的工作,如包://乌里

  • 可以直接从XAML使用

  • 将位图中的位图缓存中,同一个URI,所以未来使用不会去磁盘。在您的特定应用,这可能是一件坏事,但对其他使用它可能是一个可取的特点。

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

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