Page constructor gets called again when navigating back in Windows 8 C# App
Asked Answered
I

1

6

I have found that in Windows 8 apps, a Page's constructor always gets called again when navigating back to this page, however this is not the case in Windows Phone 7 apps.

Because of this behavior all the properties of that page get lost and you need to somehow store them and reassign them after the page is reactivated. At the moment I am using the SaveState method to save the data and reassign the data in LoadState method. Both of the methods are built-in in the sample Grid/Split App.

I wonder why it's designed this way and if there's any better way to maintain the instance of the page?

Indulge answered 28/9, 2012 at 4:51 Comment(1)
+1 for calling this out. It caught me off guard. It's a major change and means totally rethinking your state and VM lifecycle.Fizzy
M
5

You can set Page.NavigationCacheMode = NavigationCacheMode.Required for each page you want to keep in memory, but note that you have to make sure users can't navigate through these pages endlessly as that would leak memory.

Moy answered 28/9, 2012 at 6:15 Comment(2)
Thanks! Just wonder why there would be any memory issue? Is there any best practice for it?Indulge
Well, if you keep pages in memory - any memory a page holds will not be released until you remove the page from back and forward stacks. If you allocate any significant amounts of memory - you could do that in OnNavigatedTo and release it in OnNavigatedFrom, but I guess the best way is to leave it as is with no page instance caching.Moy

© 2022 - 2024 — McMap. All rights reserved.