问题
i want to know what are your strategies for saving state in a windows phone 7 (wp7) app. when i say state, i mean the model-view state of each page in the stack.
recently, i asked a question at, problems with tombstoning in WP7, cannot tell if i need to restore or instantiate/query new data, and the solution works. however, this approach seems to be ad-hoc and/or page-specific only. the code doesn't save the states of the pages preceding it.
it's my understanding that when the app is activated or deactivated, you are supposed to handle restore or backup of the app's state, respectively. the generated code-behind for App.xaml.cs generates the methods
private void Application_Activated(object sender, ActivatedEventArgs e)
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
how are we to take advantage of these methods to save an applications full state when being tombstoned? i haven't found a good tutorial yet online.
any help is appreciated.
回答1:
In practise, you might as well forget those methods. You shouldn't think of tombstoning as persisting state, more as of persisting data.
You obviously can't magically tombstone the state of your entire application. And generally speaking, the UI state of a page will only be known of the individual page.
What you need to do is to figure out what UI states you wish to persist, if any, and then persist those along with the data (obviously) in the PhoneApplicationService.State or IsolatedStorage.ApplicationSettings (depending on the size of the data).
For ViewModels, it's fairly easy to tombstone them. Just add the code to check if a tombstoned instance exists, and then load the data of the viewmodel with that upon creation. And if you bind all the UI settings to your viewmodel, you're pretty much golden.
The code from your previous question, can be used in your ViewModels constructor with pretty much the same result. And to constantly persist the ViewModel, just attach a local handler for PropertyChanged, and save the ViewModel's state every time that's called.
来源:https://stackoverflow.com/questions/6830518/tombstoning-strategy-in-windows-phone-7-how-to-save-states-of-multiple-pages