Interaction of view models in MVVM
Asked Answered
P

5

15

I have a WPF application which follows the MVVM pattern. The application defines two views and view models so far:

  • LoginView(Model)
  • ProjectsView(Model)

Both view models need to access several properties from other view models.

Example:
LoginViewModel has a property ProjectList. ProjectsViewModel needs to access this property as well.

This is only a simple example. Later there will be several UserControls which all need to interact with each other.

Would it be a better idea to create one huge view model which all UserControls (views) set as their DataContext? If not, how can all the different view models interact with each other?

Remark:
This question is closely related to this one but with a different approach.

Presidium answered 16/1, 2013 at 15:18 Comment(0)
V
51

You should definitely not make a huge "main view model" -- this is an anti-pattern not dissimilar to a god object.

The key idea here is that your viewmodels do not need to access several properties from other view models; rather, all of the viewmodels need to access specific pieces of information.

Right now you are most likely injecting this information into each viewmodel at the time of instantiation. Instead of doing this, provide each viewmodel with a reference to a service -- an application module that exposes this information through properties and/or methods. The information can be exposed in the form of scalar values if it's extremely simple in nature, or in the form of models if it's anything more complicated than that.

Schematically this would look like

/--------------\
|  ViewModelA  |
|              | <=======\
|              |         |
\--------------/         |  <--- information is pulled      /================\
                         +=========[model]===[model]======  |    Service     |
/--------------\         |                                  \================/
|  ViewModelB  |         |
|              | <=======/
|              |
\--------------/

The service should be injected into the viewmodels upon construction (either manually or by the DI container if you are using one). Each viewmodel should only require a reference to the service and enough information to tell to the service which model it's interested in; it will then request that model from the service and populate its "interesting" properties based on that.

This way of doing things is more involved than simply constructing a viewmodel object and setting its properties externally, but it will allow your application to grow in complexity without becoming unmanageable.

For example, if there are lots of views that bind on different viewmodels and these viewmodels depend in complex ways on a number of models, a sane manner to work would be:

  1. A view/viewmodel pair is constructed
  2. The viewmodel requests any models it needs to know about from the service; it subscribes to an event that the service exposes to let subscribers know that a model has changed
  3. Changes are performed to the models through databound controls
  4. The view invokes a "save" command on the viewmodel
  5. In response to that, the viewmodel invokes a "save this model" method on the service
  6. The service persists the information and publishes a "model changed" event (see step 2)
  7. Other viewmodels interested in the same model know that the model has changed and can query the service for its new state

This is possible if everything is routed through the service. Imagine what it would take to keep everything synchronized otherwise -- the only way to cope would be to put all the information into a giant viewmodel and reference that from everything else. Ugly.

Villose answered 16/1, 2013 at 15:26 Comment(13)
This sounds reasonable. Ok, now all I need to do is finding out how to implement such a service :-)Presidium
@RobertStrauch - That's the life of a programmer.Yerga
This is ok if that property is different for each ViewModel, i.e. presents the model in a different way. But if you have a single property which is valid for all Viewmodels? will you rebuild it for each of them when model changes? Accept that hierarchical viewmodels are used often.Ceramic
@Natxo: Sure, whatever floats your boat. If you want though take a look at this answer where I explain in more detail a setup that went exactly like that. It worked great and I remember it pleasantly. Was quite a bit of code to wire everything together admittedly.Villose
@Jon: That answer you linked is great, and fits exactly on how mvvvm should be implemented. I wanted to point out that you dont have to be afraid of putting general properties in the not-so-god-like object that is the MainViewModel of your MainView.Ceramic
@Jon: I really like the service idea and thanks for your other linked answer. I get the basic idea. However, I'm not sure how to implement such a service. Do you have some sample code available somewhere?Presidium
@RobertStrauch: Unfortunately I 'm not permitted to share it.Villose
@Jon: Let me summarize the service idea in my own words. There are n models. The difference is that a model (or multiple models) is not instantiated in the viewmodel itself but pulled from the service. When changing data in that model, the viewmodel pushes the model back to the service.Presidium
@Robert: Exactly. The service creates the models on demand (and it may not even own the data itself; typically it sits in front of your data provider as an additional abstraction layer).Villose
@Jon: Sorry for all the follow-up questions. I'm doing some trial and error... my service provides a method public object GetModel(xxx). What does xxx have to be, i.e. how can I say to the method: "Give me the model with that name"? Example: modelProvider.GetModel("LoginModel");Presidium
@Robert: Perhaps a generic public T GetModel<T>(...) would be better?Villose
@Jon: Just to get it right once again :-) 1. That means each viewmodel keeps a copy of the requested model(s) and as soon as one model change is pushed to the service all subscribed viewmodels refresh their copy of the model? 2. I reckon getting the models via a property is equal to using a getter method? 3. If I am right I must implemeent an additional publish/subscription mechanism?Presidium
@Robert: Yes, but you may not need to do all of that. That way worked very well for me, that's all. It is a lot of work.Villose
S
5

Usually I do one of 4 things:

  • Make my ViewModels reference each other, and pass the property around. For example, LoginViewModel might set ProjectsViewModel.ProjectList on successful login. How you implement this depends on how your ViewModels are related to each other, and where logical points of connection would be.

  • Make an ApplicationViewModel which manages things like which page is current, and application-wide objects like the current user or current project list. It would handle transferring shared data to the ViewModels that needs it.

  • Use some kind of Event system to broadcast a message anytime an application-wide property changes, and have any ViewModel that's interested subscribe to receive those messages. The message typically contains the new object as well, so anyone subscribed to receive that message type has access to the new object. (I have a brief summary of Event Systems in my blog article Communication between ViewModels with MVVM if you're interested)

  • Depending on if any of the other options work better, I may consider creating a singleton to hold application-wide data instead. For example, if the User is set on Login and is accessed from many of my ViewModels, I may create a singleton to set the user on first login, and then all my ViewModels can access it.

The one thing I would not do is make one big ViewModel holding all available data. ViewModels should only contain the data specific to it.

Seethrough answered 16/1, 2013 at 15:32 Comment(5)
Taking the first idea... could you provide a sample code snippet how to reference the view models "to each other"?Presidium
@Robert Usually I only do that with closely linked ViewModels where the connection would seem natural, such as an AllCustomersViewModel containing a reference to a SelectedCustomerViewModel.`Seethrough
Wondering why not use MainViewModel for the functions you described being handled by the ApplicationViewModel in your second option?Turves
@DeanKuga You could, it just depends on how big your project is and what is considered part of the Application, and what is considered part of the MainWindowSeethrough
@Seethrough You're right, if MainViewModel is a ViewModel of the Main Window it would make sense to pull out some App wide items out of it in a separate ViewModel. That also promotes separation of concerns...Turves
T
1

If you are using some sort of dependency injection tooling, you could inject a class that provides those values, for example, an IProjectService, that can return the list of projects on each of those view models.

The idea of one giant view model does not sound appealing, nor does strong coupling between view models by accessing each other's public properties. And if you want interaction between the view models, like when a project gets added, use a publish / subscribe model for each of the events you expect to occur.

Talyah answered 16/1, 2013 at 15:24 Comment(0)
Y
1

Your Model should contain things like a project list, or give you the ability to access it. The ViewModel is simply meant to be a layer between the Model and View, giving you the chance to bring different Model objects together and mold them into a shape which the View can readily display and to handle commands from the View (modifying the Model in response).

Yerga answered 16/1, 2013 at 15:28 Comment(2)
That idea popped into my mind as well. However, I have the problem: how do I access that same model in those view models which need it?Presidium
Make the Model object constructors internal then create a singleton "ModelObjectAccessor" class that can pass objects on request. The accessor can create a cache (which, if you are using dependency injection, can actually be implemented by the View) to ensure that there are not unnecessary repeated calls to the database.Yerga
C
1

Create one Base View Model keep all common Properties in that, Create singleton to BaseViewModel and add that singleton property in all View Models. All Viewmodels will get synced at one time.

Cerda answered 1/3, 2017 at 9:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.