WP7 -persiting the same base viewmodel when navigating to a new view

Mar 1, 2011 at 3:02 PM
Edited Mar 1, 2011 at 3:24 PM

Hi guys/gals,

I'm trying to wrap my head around how to implement one viewmodel for two different views or pages, when navigating from the first page to a second page, and then back to the first page. Ive had a look at the documention over and over, and lthough there seems to be much for dealing with the ViewModel first paradigm, I am strugling to see any solution to my WP7 View first problem.

In the documentation, it seems possible to change the LocateForViewType function, however, does this still mean that my MainViewModel with go through the whole lifecyle of deactivating, being tombstoned, and then reactivated once it needs to be attahed to my second view or page. 

I think its important to state here that I would like to preserve the viewmodel between page navigations, and not have to use a contentcontrol to host the aditional view/page.

I hope I am making sense. :)

Thanks in advance.

Maria

 

Mar 1, 2011 at 5:07 PM

Actually, in WP7 version of CM, the navigation between pages is handled in a view-first fashion (see the INavigationService section in the WP7 doc), since the WP7 navigation infrastructure is not very customizable.
In other words, CM lets WP7 to create views, then hooks a corresponding VM after navigation has been completed.
Since there is no conductor handling the VM lifecycle for a longer time, the VM has to be activated and deactivated within the lifespan of the view. 
Passing through a activation and deactivation, however, doesn't prevent the VM to be used again (if the instance is kept alive somewhere): its state is not affected by the execution of lifecycle methods.

So I suggest you to cache the instance of the VM (or register it as singleton in the container, if applicable) and customize LocateForViewType method in order to provide the cached instance instead of a new one.

Is this an acceptable arrangement for you? 

Mar 1, 2011 at 5:21 PM

Great this sounds fine thank you very much. :)  You have certainly clarified this up for me.