SoFunction
Updated on 2025-03-07

MVVM simplified Messager class instance code

Preface

When developing Wpf/SL applications, you often encounter the problem of passing parameters between different pages and forms. For this type of problem, we generally implement data transmission through events, and we can also define global static variables for data sharing. Here we use another very efficient and elegant method for messaging. I call it Messenger here. In fact, Messenger is not a patent of mvvm. We can regard it as a design pattern, and you can use it in other .net programs.

Simplify the Messager class

Looking at the MVVMLight Messager source code, I implemented a simple Messager class myself.

The Messager class can realize the communication between View and VM, VM and VM, View and View in MVVM.

public class Messager
{
 private static Messager _MessageInstance;
 private Dictionary<string,Action> _MessageCollection=new Dictionary<string,Action> ();
 private Dictionary<string, ActionClass> _MessageTCollection = new Dictionary<string, ActionClass>();

 public static Messager Default
 {
  get
  {
   if (_MessageInstance == null)
   {
    _MessageInstance = new Messager();
   }
   return _MessageInstance;
  }
 }

 public void Register(string key,Action action)
 {
  _MessageCollection.Add(key,action);
 }

 public void Register<T>(string key, Action<T> action)
 {
  ActionClass<T> actionClass = new ActionClass<T>();
   = action;
  _MessageTCollection.Add(key, actionClass);
 }

 public void Send(string key)
 {
  if (_MessageCollection.(key))
  {
   _MessageCollection[key].Invoke();
  }
 }

 public void Send<T>(string key,T para)
 {
  if (_MessageTCollection.(key))
  {
   ActionClass<T> actionClass=(ActionClass<T>) _MessageTCollection[key];
   (para);
  }
 }
}

It is mainly registered through the Register method and the Send method is triggered.

For example, a form needs to be displayed in the VM. In order not to destroy the MVVM mode, we can write the method of displaying the form in the View and register it in the Messager.

<string>("ChangeControlShow", ExecuteChangedContrlShow);
private void ExecuteChangedContrlShow(string msg)
{
//some code...
}

Called in VM

<string>("ChangeControlShow","test");

Send has two parameters. The first is the key of the method. According to this key, the only method can be found, and the second parameter is the parameter of the method that needs to be called.

In this way, as long as you know the key of the method, you can call the registered method in any file, and we don’t need to use the delegation anymore.

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.