I am following the general best practice principles of restoring my persistent and none persistent state and objects when a tombstoned app is re-activated. Which can be found in this very good Microsoft article
here
The samples only show a simple re-activation of the main page of an app. However as my application has multiple pages (any of which could be tombstoned and therfore re-activated) and each one is binding to a different ViewModel object. I would like to know how to asce开发者_运维百科rtain which page is ultimately going to be activated so that I can selectivly deserialize and recover the correct ViewModel object for that page.
Or is the best practice to restore all ViewModels or is there another design pattern for this?
I have implemented a simple pattern that is best described as -
- In the application's Activated and Deactivated event, I send a message to subscribing pages.
- The pages that subscribe to the message do the serialization/deserialization of data.
I am using Laurent Bugnion's excellent MVVMLight library for Windows Phone 7. Here is some sample code illustrating the message broadcast -
// Ensure that application state is restored appropriately
private void Application_Activated(object sender, ActivatedEventArgs e)
{
Messenger.Default.Send(new NotificationMessage<AppEvent>(AppEvent.Activated, string.Empty));
}
// Ensure that required application state is persisted here.
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
Messenger.Default.Send(new NotificationMessage<AppEvent>(AppEvent.Deactivated, string.Empty));
}
Within the constructor of a ViewModel class, I setup the subscription to the notification messages -
// Register for application event notifications
Messenger.Default.Register<NotificationMessage<AppEvent>>(this, n =>
{
switch (n.Content)
{
case AppEvent.Deactivated:
// Save state here
break;
case AppEvent.Activate:
// Restore state here
break;
}
}
I found that with this strategy, all the data relevant to the page that is bound to a ViewModel is saved and restored properly.
HTH, indyfromoz
精彩评论