Skip to main content

Layer Communication. Messenger

  • 2 minutes to read

Note

MVVM Best Practices Demo The text below has a related example in the DevExpress ‘MVVM Best Practices’ demo.

Group: API Code Examples

Module: Messenger

Example: Messenger

24.2 Demo Center: Launch the demo

Your real-life applications will almost always have multiple Views and ViewModels. And, with rare exceptions,you will need a way for these separate layers to communicate with each other and share data. To solve this task, use the DevExpress MVVM Messenger.

The idea of this message mechanism is very simple: in the sender ViewModel, you call the Send method to transmit required data as a message. In the recipient ViewModel, the Register method is called to catch all messages.

//sender
public void SendCustomMessage() {
        Messenger.Default.Send("A message");
}

//receiver
public void RegisterAsStringMessageRecepient() {
        Messenger.Default.Register<string>(this, OnStringMessage);
}
void OnStringMessage(string message){
        //custom action
}

The Register method establishes a permanent connection between your ViewModels. This means once called, the Register method does not need to be called ever again - all consequent messages sent will be received automatically. To break this connection, use the Unregister method.

Messenger.Default.Unregister<string>(this, OnStringMessage);

If there are multiple senders that transmit messages of the same type, you can use tokens to label messages sent from different senders. Tokens can be objects of any type, the code below uses simple string tokens.

public void TransmitMessage1() {
    Messenger.Default.Send<string>("This message is sent from Sender 1", "sender1");
}

public void TransmitMessage2() {
    Messenger.Default.Send<string>("This message is sent from Sender 2", "sender2");
}

The Register and Unregister methods have corresponding overloads that allow you to receive or block messages marked with the specific token.

Messenger.Default.Register<string>(this, "sender1", OnStringMessage);
Messenger.Default.Unregister<string>(this, "sender2", OnStringMessage);