简体   繁体   中英

Lost DataContext when navigating back in Frame (SplitView) in UWP

I'm writing an Universal App in C# for Windows 10 using the SplitView with a frame for navigation. I have a sidebar with a list that I load dynamically and, when I click on one of the items, I navigate to a page using the model from the menu to indicate which item I should load in the Frame.

I followed this sample: Windows-universal-samples/Samples/XamlNavigation/

The only difference is, instead of having multiple pages, I have only one page that is loaded every time I select a different item with its specific ViewModel. I use Autofac to load the ViewModels and MyFrame.Navigate(typeof(DetailsPage), idOfItem); to load the page.

The problem is, every time I navigate to the next page, it seems that the instance of the previous one is lost and when I navigate back, it loads a new instance. This kind of thing doesn't seem to happen when I'm navigating in the RootFrame and it didn't happen in Windows Phone 8.1.

I've been searching for a solution on the Web for hours, but I can't find anything relevant.

Does anyone know why this could be happening? I hope I was clear enough with my question.

Thank you in advance for the answer.

The behavior you observe is correct and as expected. You have two options:

You can use Page.NavigationCacheMode , set it to Required . This is easy, but may consume a lot of memory.

Or you can save page state in OnNavigatedFrom and restore it in OnNavigatedTo . In fact, depending on your scenario, it may not even be necessary to save state in OnNavigatedFrom, assuming the state (your DataContext) can be constructed when returning to the page in the same way that you constructed it when first comming to the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM