检测页面是否已初始化并使用它而不是创建新实例 [英] Detecting if a page has already been initialized and using it instead of creating a new instance

查看:101
本文介绍了检测页面是否已初始化并使用它而不是创建新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写的C#WPF应用程序严重依赖于框架控件中托管的页面。通过使用frame.Navigate(new pageName());单击各自的菜单项来访问页面。但这意味着每次用户想要返回页面时(这是很多次)我必须在页面切换之前重新加载界面中的所有数据。目前我正在使用一个单独的XML文件,其中包含每个页面在更改之前的所有数据,然后由页面加载的事件检查并重新加载到控件中。有没有更好更简单的方法来反复访问页面而无需创建它的新实例?



我可以使用public pageName初始化所有页面pagename = new PageName();但它可能会耗尽不必要的内存,如果用户从未访问其中一个页面就会浪费。



我可以继续初始化页面的新实例在其菜单点击事件,但检查它是否已经初始化并在创建新的之前使用它。



我可以继续使用我保存到文件的方法在下一次加载页面时从它上载。



我认为第二个是最好的,但我不知道如何检查我想要的页面是否已经存在初始化并可以使用。我使用它来获取窗口的当前实例:var MainWindow = Application.Current.Windows.Cast()。FirstOrDefault(window => window is MainWindow)as MainWindow;但它不适用于页面。基本上我只是想知道如果页面的当前实例已经初始化而不是每次需要访问它时都创建一个新实例,我该如何使用它。

解决方案

尝试使用导航历史记录和 Page.KeepAlive 。这是MSDN链接:

http: //msdn.microsoft.com/en-us/library/ms750478(v=vs.110).aspx#NavigationHistory

The C# WPF application I am writing is heavily dependant on pages hosted inside a frame control. The pages are accessed by clicking their respective menu items with frame.Navigate(new pageName()); But this means that each time the user wants to go back to a page (which is quite a lot of times) I have to reload all of the data that was in the interface before the page was switched. Currently I am using a separate XML file containing all the data for each page before it is changed which is then checked by the page' loaded event and reloaded into the controls. Is there a better and easier way to access pages over and over again without having to create a new instance of it?

I could initialize all of the pages with public pageName pagename = new PageName(); but it would probably use up unnecessary memory and it would be wasted if the user never accessed one of the pages.

I could carry on initializing a new instance of the page in its menu click event but check if it is already initialized and use that instead before creating a new one.

I could continue using my method of saving to a file and loading from it on the next load of the page.

I think the second one is best but I have no idea how to check if the page I want has already been initialized and can be used. I use this for getting the current instance of a window: var MainWindow = Application.Current.Windows.Cast().FirstOrDefault(window => window is MainWindow) as MainWindow; but it doesn't work for pages. Basically I just want to know how I can use the current instance of a page if it has already been initialized instead of creating a new one each time it needs to be accessed.

解决方案

try to use navigation history and Page.KeepAlive. Here is MSDN link:
http://msdn.microsoft.com/en-us/library/ms750478(v=vs.110).aspx#NavigationHistory.


这篇关于检测页面是否已初始化并使用它而不是创建新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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