Search code examples
navigationwindows-phone-8.1lifecyclesavestate

NavigationHelper_SaveState vs OnNavigatedFrom


The Basic Page Template for Windows Phone 8.1 has the following methods:

private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
protected override void OnNavigatedTo(NavigationEventArgs e)
protected override void OnNavigatedFrom(NavigationEventArgs e)

My understanding is that the NavigationHelper methods above are used to save page data in NavigationHelper_SaveState so that it is available the next time the page is loaded, in NavigationHelper_LoadState.

And that OnNavigatedFrom is used to perform any last second tasks, and OnNavigatedTo is used to perform any starting tasks. But also, the OnNavigatedFrom method contains the data passed in from the Frame.Navigate() method in the previous frame.

My question is, am I correct in thinking that the first 2 methods are used for maintaining data within a single page, and the second 2 methods are used for transferring data between the 2 pages?


Solution

  • I'll try to explain a little how it works and where it's usefull.

    First, all the methods you have mentioned are connected with eachother, more - it also involves SuspensionManager. Look that the methods (eventhandlers): NavigationHelper_LoadState nad NavigationHelper_SaveState of a single Page are run from Navigation events. They are subscribed to event in page's constructor:

    this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
    this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
    

    and they are fired in `Navigation events* by calling NavigationHelper's method:

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
       this.navigationHelper.OnNavigatedTo(e);
    }
    // inside the method event is fired:
    if (this.LoadState != null)
    {
        this.LoadState(this, new LoadStateEventArgs(e.Parameter, null));
    }
    

    LoadState and SaveState are helpers that should make easier to recover your Page. Whn it's usefull? - when your Page's resources are being freed and after some time you want to bring it back. Simple examples: you use FilePicker, ShareTarget, your app has been suspended and its resources freed, then when you activate your app (which should bring back your Page) there may be need to recover resources of a page (for example those which you have passed via parameter during navigation).

    Note also that those cases involve also SuspensionManager and you should pay attention to restoring your app in App.xaml.cs (OnLaunched, Activated and other).

    Note also that those templates are only helpers and you may need a dfferent behaviour which you can surely implement yourself.

    Some resources at MSDN: Lifecycle, Launching, resuming, and multitasking and Guidelines for app suspend and resume.