man

How does ViewModel interact with View?

In addition to the binding mechanism, a ViewModel can communicate with a View using other mechanisms such as Behavior, Messenger, or through interfaces implemented by the View and introduced into the ViewModel.

By extending the Behavior class, we can provide DependencyProperties along with regular properties that we can bind to properties from the ViewModel, so that when the properties of the ViewModel change, we can execute user interface code. The advantages of Behavior objects are that they can be easily reused, they are “blended” and allow us to move the code behind the View.

MVVM Light offers a Messenger class that is used by various objects to communicate in the application through a low-level communication mechanism. Messages can contain simple data types or more complex ones. This class is often used to allow ViewModel objects to communicate or to allow ViewModel objects to communicate with a View.

Another approach is to create interfaces that will be implemented by the View. For example, if we want to display notifications in a View, we can create an interface that exposes these methods, implement it in the View, and then add it to the ViewModel (we can get a reference to the ViewModel using the DataContext property).

It should be noted that the preferred way to handle this communication is with Behaviors, although MVVM does not explicitly state this, it is clear that as long as the code behind is minimized, the program is easier to test. The downside of Behaviors. is that they are not available in Windows 8 out of the box, so the code will be less portable, but there are libraries that offer classes similar to Behavior classes.