问题
I have a Frame in MainPage, and there's content in MainPage, for example, a List which is dynamically generated by a function (let's call it loadList()) which is invoked by the Loaded event of MainPage.
After user clics on any items in the List, The Frame could be navigated to another page (lets call this DetailPage). Every time I navigate back to the MainPage from DetailPage, the MainPage invokes the Loaded event, therefore invokes the loadList() again.
My question is, that, is there any way I can keep the status of the content and keep it from being generated again once it is generated?
回答1:
By default in UWP pages are unloaded when the user navigates from them. This is useful because it conserves memory. When the user returns to the page, the page is loaded again.
You can change this behavior by setting the NavigationCacheMode propertyon your page:
<Page
...
NavigationCacheMode="Required">
If you set NavigationCacheMode to Enabled or Required, the page will be cached and will be restored when user navigates back to it. The page's Loaded event will still be called, but you can just check if the data is already initialized or not either by checking the control directly or by checking a bool flag variable you set after initialization:
private void MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
if (!initialized)
{
loadList();
initialized = true;
}
}
Difference between Enabled and Required is that Enabled honors the CacheSize setting on your Frame. Once there is more cached pages stored than the limit, the Frame will automatically remove the oldest one from memory. Required pages however don't count towards this limit and are never removed.
A slightly better alternative to this solution would be to use the MVVM design pattern. In this pattern data for your views are stored inside ViewModel classes and many MVVM frameworks maintain the ViewModels for the pages in your navigation stack in memory. This means that your page will be reloaded, but the data will be already available in the view model, so it will load fast. MVVM is the recommended pattern for developing UWP apps so I highly recommend you to try out either Prism, MvvmLight or MvvmCross.
来源:https://stackoverflow.com/questions/48847295/how-do-i-keep-the-status-of-content-during-the-navigation