When your application is suspended and then terminated it should restore its state.
You can use the following approach to save/restore a Page view model state:
public class MyPageModel : PageModel
{
private bool _isStateLoaded;
public override async void OnNavigated()
{
base.OnNavigated();
await LoadState();
Application.Current.Suspending += OnSuspending;
}
public override void OnNavigating(ref bool cancel)
{
base.OnNavigating(ref cancel);
if (!cancel)
{
Application.Current.Suspending -= OnSuspending;
SaveState().ContinueWith(task =>
{
if(task.Exception != null)
Debug.WriteLine(task.Exception);
});
}
}
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
await SaveState();
deferral.Complete();
}
private async Task SaveState()
{
// Save your state here.
}
private async Task LoadState()
{
if(_isStateLoaded)
return;
// Load your state here.
_isStateLoaded = true;
}
}
ExplanationThe view model state is saved in the Application.Suspending event handler.
The state is restored in the OnNavigated method overload. This method is called when a user navigates to the page and when the navigation history is restored.
You can also save the state in the OnNavigating method overload to restore it when a user comes to the page again. This method is called when user leaves the page.
To save/restore the navigation history you should use NavigationState.Get/SetNavigationState methods (NavigationState is usually a part of a root view model or an utility class).
You can use the following code in your App class (App.xaml.cs file).
saving:
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
string navigationState = RootModel.Navigation.NavigationState.GetNavigationState();
await Save("NavigationStack", navigationState);
deferral.Complete();
}
restoring:
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
RootModel = new RootModel ();
var frame = new Frame { DataContext = RootModel };
ElementBinder.SetWrapper(frame, RootModel.Navigation.NavigationState);
Window.Current.Content = frame;
Window.Current.Activate();
// Open a main page or restore the navigation history.
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
var history= await Load<string>("NavigationStack");
RootModel.Navigation.NavigationState.SetNavigationState(history);
}
else
{
RootModel.Navigation.GotoMainPage();
}
}