[WP7]Persisting/Reusing ViewModel between navigation.

Topics: UI Architecture
Jun 18, 2011 at 9:44 PM

Is it possible to reuse or persist ViewModel instances between page navigation.

Something like:

  1. Navigate to page. New VM is created.
  2. Navigate back.
  3. Navigate to page, while reopening same instance of previous VM, then binding it to new Page.

What I want to achieve is to persist state of UI so user can navigate out and in at will, but still have same inputs/loaded data. And also to run some code in the background, even when VM is not bound to any View. What would be the most natural/simple way of doing this?

Also Iam not looking for singleton. There will be different instances of VM created with different parameters. But when I try to open one with parameters, that already exist, then I return the old one. Something like factory pattern.

Jun 21, 2011 at 1:57 PM

To plug this behaviour you can customize ViewModelLocator.LocateForViewType delegate.
It takes care (just after navigating to a page) of locating an appropriate VM instance based on the page instance.

The VM type is inferred using naming conventions from the page type, then the instance is actually created by the container.
Another probably useful hook point is in FrameAdapter.OnNavigated method, which is the one responsible of starting the ViewModel location and binding.

You can use a cache to keep some VM instances alive and provide an existing instance instead of a new one where appropriate.

Hope it helps.