Why can’t ViewModels communicate with each other

mvvmwpf

Can someone explain concretely why it is not desirable for ViewModels to communicate directly with other view models? It seems to me that for virtually any UX application there will be a “root” view (with its ViewModel) and any further views will be somehow initiated from from this view/ViewModel, or a sub view/viewModel.

The recommendation seems to be that any communication between ViewModels takes place via a message bus or event aggregator but I can’t help but think this is overkill. For example, say we have an application that lets users define different profiles and do other actions based on the current profile. In this example the main window is dependent on something handling the profile management. Obviously i don’t want to hard core the ProfileManagerViewModel as a dependent of the MainViewModel but it seems to me that simply creating an interface (e.g. IProfileManager) is isomorphic with sending a message over a bus or aggregator. And if these are isomorphic then the interface is much easier to implement and maintain.

Even if it’s not completely isomorphic, it strikes me as a YNGNI situation: in what scenarios will I gain something extra from using an event aggregator over an interface and how likely is my application to ever encounter these scenarios during its expected lifetime? I would expect the common case to be that if my interface must change somehow (whether my interface be a C# interface or an event that I use to signal) both ViewModels will require modification anyway.

So what am I missing here? The only case I can think of is if additional viewModels were interested in e.g. the ProfileManager from my example being started but I don’t expect this to be a common situation in most applications. Of course if one sees the use of event aggregators as not adding any complexity then this whole question probably doesn’t make much sense but I think most people would see a standard interface solution radically easier to follow and reason about.

Best Answer

Views and ViewModels are meant to be reuseable components that you can combine together in different ways.

If you hardcode a command on VM1 to always update VM2 then you break that reusuablity.

But this doesnt mean that you can't have a master view model which links all the components of a page together. Or sub view models which link a set of controls together.

That kind of linking is done outside of the VMs themselves and as such doesnt introduce any hard coupling between them.

Related Topic