Layer Communication and 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.
Your real-life applications will almost always have multiple Views and ViewModels. Use the DevExpress MVVM Messenger to implement communication between separate layers and share data.
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 RegisterAsStringMessageRecipient() {
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.
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", "token1", OnStringMessage1);
}
public void TransmitMessage2() {
Messenger.Default.Send<string>("This message is sent from Sender 2", "token2", OnStringMessage2);
}
void OnStringMessage1(string message){
//custom action
}
void OnStringMessage2(string message){
//custom action
}
The Register
and Unregister
methods have corresponding overloads that allow you to receive or block messages marked with the specific token.