Articles

Communication between ViewModels

At one moment I was stuck in the MVVM development because I couldn't, or better I didn't know how to, communicate between my ViewModels. Untill I found the MVVM Foundation Messenger class.
I actually found it via this link when looking how to accomplish ViewModel communication. Mostly it's the same only I've extended the example with how to pass a parameter with it.

Example

Use the Messenger class of MVVM Foundation and include it in your project. Or add the complete MVVM Foundation project.

Create a static ViewModelCommunication class:

  public static class ViewModelCommunication
  {
    static ViewModelCommunication()
    {
      Messaging = new Messenger();
    }

    public static Messenger Messaging { get; set; }


    // message properties
    public static string LogInChanged { get { return "LogInChanged"; }

    }
  }

 

ViewModel A Registers to a Message in the ViewModelCommunication class:

ViewModelCommunication.Messaging.Register(ViewModelCommunication.LogInChanged, ActivateTabs);

ActivateTabs is just a method that changes a property. You can do all sorts of actions in the method.

 

ViewModel B notifies that the Message has been changed:

ViewModelCommunication.Messaging.NotifyColleagues(ViewModelCommunication.LogInChanged);

ViewModel A will pick this up and execute the method ActivateTabs.

 

Pass a parameter from one ViewModel to another.

ViewModel A Registers to a Message in the ViewModelCommunication class and sets a local property with the passed parameter:

ViewModelCommunication.Messaging.Register(ViewModelCommunication.LogInChanged, (Action<String>)(param => MyLocalProp = param));

 

 ViewModel B notifies that the Message has been changed and passes a parameter with it:

ViewModelCommunication.Messaging.NotifyColleagues(ViewModelCommunication.LogInChanged, "This is a parameter value");

ViewModel A will pick this up and put the passed variable "This is a parameter value" in the MyLocalProp property. From here you can trigger any action that you want.