tommitytom
Topic Author
Posts: 1
Joined: 04 Nov 2021, 05:55

Sharing model between multiple view models - best practices

04 Nov 2021, 06:09

I have a piece of shared state from our engine (resource manager, etc) that I would like to be accessible from multiple view models. Currently we are creating the view models from the view, as is described in all of the samples. Since the view model is created from the view, I can't pass state through to its constructor (since the view doesn't know this piece of state either - and I'm guessing it shouldn't). What is best practice for getting this shared state in to the view model? Before someone suggests it: singletons are not an option ;)

Any help appreciated!
 
User avatar
sfernandez
Site Admin
Posts: 2984
Joined: 22 Dec 2011, 19:20

Re: Sharing model between multiple view models - best practices

04 Nov 2021, 12:20

Ideally you only create the viewmodel from the view for the main window. That would be the application main viewmodel, and the rest of viewmodels are exposed by the main viewmodel as properties and collections that are bound to the corresponding controls, it should be like a hierarchy of viewmodels.

For example you can have a MainViewModel that exposes an ActiveScreen property, and it sets the current viewmodel there depending on the game state. And the UI will show using DataTemplates the corresponding screen views.

Does that help?
 
User avatar
ttermeer-reboundcg
Posts: 17
Joined: 13 Sep 2019, 11:10
Contact:

Re: Sharing model between multiple view models - best practices

04 Nov 2021, 16:01

Before someone suggests it: singletons are not an option ;)
What you trying to do is share data across multiple instance. This is what a singleton is designed for.
But be aware that a singleton can take multiple form.

We personally use dependency injection for our view models. Our managers are declared as single within the DI system and used to query data/state for the game.
However should that data change after initialization, we use a messaging/event system to notify the view model that in turn notify the UI via property changed event.

Who is online

Users browsing this forum: No registered users and 85 guests