MVVM Communication Between Views – C# and WPF Guide

cmvvmwpf

I know we can use the Mediator Pattern to communicate between view models but what about views?

Lets assume I have a button in View A which should trigger functionality of View B. How is this preferably done? I could use the Mediator but it seems more like a hack.

Here is a thought of mine:

enter image description here

Best Answer

Lets assume I have a button in View A which should trigger functionality of View B.

According to the MV(V)C Pattern there should not by any "functionality" in any View.

The functionality should be in the controller layer which handles the applications state by altering the model as needed.

Now you can have as many view layers (in parallel or sequentially) viewing the model data and manipulating them via the controller.

Since the model provides infrastructure to propagate changes the View B can register for certain Properties to get change information so that it can update itself when View A changed that property.


So for functionality I have extra classes called (some prefix)ViewController? Do we also have controller for viewmodels? (ViewModelController) – Asperger

Do not put your fath on that names. After all names are just dust in the wind.

The point is that you have to deal with this 3 layers model, controller, and view. The different names (MVC,MVVC, MCP) are only variation and don't mean that much to me.

You also do not necessarily put them into separate projects, packages or classes. The pattern is basically about the direction of communication:

  • the model does never talk to anything else directly, only via interfaces it provides itself (mainly getter/setter methods and *Listener interfaces).
  • the controller only talks to the model via the models interfaces.
  • the view gets data (and change information) to display from the model and translates user input to calls in the controller layer. It never updates the model itself.