Skip to main content

DevExpress v24.1 Update — Your Feedback Matters

Our What's New in v24.1 webpage includes product-specific surveys. Your response to our survey questions will help us measure product satisfaction for features released in this major update and help us refine our plans for our next major release.

Take the survey Not interested

Messenger

  • 9 minutes to read

The DevExpress.Mvvm.Messenger class allows you to implement a message exchange between modules.

The Messenger class implements the IMessenger interface.

Run Demo: Messenger

#Getting Started With Messenger

The following step-by-step tutorial illustrates how to use the DevExpress.Mvvm.Messenger to send notifications from one module (ViewModel) to another:

  1. Create a Sender and Receiver View and ViewModel.

    using DevExpress.Mvvm;
    
    namespace MVVMDemo.ViewModelsInteraction {
        // Sender ViewModel
        public class SenderViewModel {
            // ...
        }
    
        // Receiver ViewModel
        public class ReceiverViewModel {
            public virtual string ReceivedMessage { get; protected set; }
            // ...
        }
    } 
    
    <UserControl x:Class="MVVMDemo.ViewModelsInteraction.MessengerView"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:local="clr-namespace:MVVMDemo.ViewModelsInteraction"
                 xmlns:dxlc="http://schemas.devexpress.com/winfx/2008/xaml/layoutcontrol"
                 xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm">
        <dxlc:LayoutControl Orientation="Vertical" VerticalAlignment="Top">
    
            <!-- A layout group bound to the SenderViewModel -->
            <dxlc:LayoutGroup DataContext="{dxmvvm:ViewModelSource local:SenderViewModel}"   Header="Sender" Orientation="Vertical" View="GroupBox">
                <!-- Click the button to send a message -->
                <Button>Send Message</Button>
            </dxlc:LayoutGroup>
    
            <!-- A layout group bound to the ReceiverViewModel -->
            <dxlc:LayoutGroup DataContext="{dxmvvm:ViewModelSource local:ReceiverViewModel}"   Header="Receiver" Orientation="Vertical" View="GroupBox">
                <TextBlock Text="{Binding ReceivedMessage}" />
            </dxlc:LayoutGroup>
    
        </dxlc:LayoutControl>
    </UserControl> 
    
  2. Implement a method that sends messages (SendMessage in a code sample below). Bind the Send Message button within the Sender View to the method.

    using DevExpress.Mvvm;
    
    namespace MVVMDemo.ViewModelsInteraction {
        // Sender ViewModel
        public class SenderViewModel {
          // The DevExpress MVVM framework generates commands for public methods.
          public void SendMessage() {
              Messenger.Default.Send("Hello world!");
          }
        }
    } 
    
    <!-- A layout group bound to the SenderViewModel -->
    <dxlc:LayoutGroup DataContext="{dxmvvm:ViewModelSource local:SenderViewModel}"   Header="Sender" Orientation="Vertical" View="GroupBox">
        <!-- Click the button to send a message -->
        <Button Command="{Binding SendMessageCommand}">Send Message</Button>
    </dxlc:LayoutGroup>
    
  3. Enable the Receiver View Model to get messages. The ViewModel’s ReceivedMessage property value is set to the message text.

    public class ReceiverViewModel {
        public virtual string ReceivedMessage { get; protected set; }
        // Subscribe to the Messenger. 
        // Run the 'OnMessage' method when a message is received.
        protected ReceiverViewModel() {
            Messenger.Default.Register<string>(this, OnMessage);
        }
        void OnMessage(string message) {
            ReceivedMessage = "Received: " + message;
        }
    }    
    

The animation below illustrates the result.

Messenger Service animation

#Default Messenger

The static Messenger.Default property returns a default Messenger instance. The default messenger is not multi-thread safe and stores weak references.

#Change the Default Messenger

To change the Default messenger, create a new Messenger instance and pass is to the static Messenger.Default property. For example, the following code replaces the Default Messenger with a multi-thread safe Messenger:

public partial class App : Application {
    public App() {
        Messenger.Default = new Messenger(isMultiThreadSafe: true, actionReferenceType: ActionReferenceType.WeakReference);
    }
}

#Send and Receive Messages

Use the following methods to send and receive messages:

public static void Register<TMessage>(this IMessenger messenger, object recipient, Action<TMessage> action);
public static void Send<TMessage>(this IMessenger messenger, TMessage message);

The code sample below demonstrates how to send and receive messages of different types.

public class MyMessage {
    //...
}
public class Recipient {
    public Recipient() {
        // Receives messages of the `string` type.
        Messenger.Default.Register<string>(this, OnMessage1);
        // Receives messages of a custom `MyMessage` type.
        Messenger.Default.Register<MyMessage>(this, OnMessage2);
    }
    void SendMessages() {
        // Sends messages of the `string` type.
        Messenger.Default.Send("test");
        // Sends messages of a custom `MyMessage` type.
        Messenger.Default.Send(new MyMessage());
    }
    void OnMessage1(string message) {
        //...
    }
    void OnMessage2(MyMessage message) {
        //...
    }
}

#Send and Receive Message Descendants

When you subscribe to a message of a custom type, you can invoke your handler if a message descendant is received.

Use the following methods to work with the messages of custom inherited types.

public static void Register<TMessage>(this IMessenger messenger, object recipient, bool receiveInheritedMessagesToo, Action<TMessage> action);
public static void Send<TMessage>(this IMessenger messenger, TMessage message);

The code sample below demonstrates how to invoke a handler when a message descendant is received.

public class InheritedMessage : MyMessage {
    // ...
}
public class Recipient {
    public Recipient() {
        // Inherited messages are not processed with this subscription
        Messenger.Default.Register<MyMessage>(
            recipient: this, 
            action: OnMessage);
        // Inherited messages are processed with this subscription
        Messenger.Default.Register<MyMessage>(
            recipient: this, 
            receiveInheritedMessagesToo: true,
            action: OnMessage);
    }
    void SendMessages() {
        Messenger.Default.Send(new MyMessage());
        Messenger.Default.Send(new InheritedMessage());
    }
    void OnMessage(MyMessage message) {
        // ...
    }
}

#Messages With Tokens

You can invoke message handlers when a message with a particular token is received. Use the following methods to work with messages with tokens:

public static void Register<TMessage>(this IMessenger messenger, object recipient, object token, Action<TMessage> action);
public static void Send<TMessage>(this IMessenger messenger, TMessage message, object token);

The code sample below demonstrates how to invoke handlers when a message with an appropriate token is received.

public enum MessageToken { Type1, Type2 }
public class Recipient {
    public Recipient() {
        Messenger.Default.Register<MyMessage>(
            recipient: this, 
            token: MessageToken.Type1,
            action: OnMessage1);
        Messenger.Default.Register<MyMessage>(
            recipient: this, 
            token: MessageToken.Type2,
            action: OnMessage2);
    }
    void SendMessages() {
        Messenger.Default.Send(message: new MyMessage(), token: MessageToken.Type1);
        Messenger.Default.Send(message: new MyMessage(), token: MessageToken.Type2);
    }
    void OnMessage1(MyMessage message) {
        //...
    }
    void OnMessage2(MyMessage message) {
        //...
    }
}

#Unregister Message Handlers

#Messenger With Weak References

You do not need to unregister message handlers if you use a Messenger with weak references (for example, the Default Messenger). Subscribing to messengers with weak references does not cause memory leaks.

#Messenger With Strong References

You can use a Messenger instance that works with strong references:

Messenger messenger = new Messenger(isMultiThreadSafe: false, actionReferenceType: ActionReferenceType.StrongReference);

To avoid memory leaks, unregister message handlers with any of the following methods:

// Unsubscribe from a specific message
void IMessenger.Unregister<TMessage>(object recipient, object token, Action<TMessage> action);
// Unsubscribe a recipient from all messages
void IMessenger.Unregister(object recipient);

#Closures in Message Handlers

The weak reference messenger (like the Default messenger) imposes a limitation for lambda expressions with outer variables (closures).

The weak reference messenger refers to a lambda expression with a weak reference. If the garbage collector collects the lambda expression object, the message handler is not invoked.

In the code below, the lambda method refers to the text variable that is defined outside the lambda. In this case, this lambda can be collected and never called.

public class Recipient {
    public Recipient(string text) {
        // WARNING!
        // The lambda may be collected and never called.
        Messenger.Default.Register<Message>(this, x => {
            var str = text;
            //...
        });
    }
}

To protect a lambda expression object from being collected, declare the text variable as a property at the subscriber object level, for example:

public class Recipient {
    string MyProperty {get; set;}
    public Recipient(string text) {
        MyProperty = text;
        Messenger.Default.Register<Message>(this, x => {
            var str = MyProperty;
            //...
        });
    }
}

You can also store the message handler as follows:

public class Recipient {
    Action<Message> messageHandler;
    public Recipient(string text) {
        messageHandler = x => {
            var str = text;
            //...
        };
        Messenger.Default.Register<Message>(this, messageHandler);
    }
}

If your lambda expression does not use outer variables, your message handler is invoked without any limitations.