Viewmodel State

Sep 16, 2010 at 8:34 AM

I have a view model which presents a list of items on a bing map. The bing map is hooked up to a weather service which displays weather conditions in major cities in my view. The view model needs to transition between a number of different views, however I do not want to lose the state of the weather service data on the view model. How would I go about this?

One way of doing this might be to create a singleton view model, so that the same instance of the view model is being used when it is bound to a number of views. Would this be a viable solution? If it is how can I make a view model singleton?

Sep 16, 2010 at 10:07 AM

I normally tend to shy away from static ViewModels, because you could would end up extending the lifetime of the Views creating (short-term?) memory leaks. So the way I go about is, either:

1. Have a parent View/ViewModel - now, a parent's data-context normally cascades down to the child Views. This way, your child Views can all share the same ViewModel - if you look at the sample I posted in this post (, I created a Wizard parent View/VM and the child Views shared the parents VM. 

2. Pass-along the data - one of the things you can do with nRoute is pass-along data whilst navigating as navigation parameters. So I suppose when transitioning from one View to another you can send along the shared state, this way each view can do it's thing and pass along the shared state. See step 8 in this post (

3. Shared static resource - one technique I've used elsewhere is that I've create an instance of the shared state as either an application or parent resource. So something like:

                <local:MyState x:Key="SharedState" />

That given resource will be available to all your Views.


Oct 13, 2010 at 8:00 AM

Rishi's point about lifetime is very valid - if you are aware of this and have a good reason to do so then you could also consider the solution i posted in this thread, which allows attribute driven persistant ViewModels, in line with the rest of the nRoute framework