Skip to content

Messenger

Rico Suter edited this page Jun 3, 2015 · 2 revisions
  • Package: MyToolkit
  • Platforms: All (PCL)

The messenger is mainly used to send events from the view model to the view in a decoupled way. In the default scenario, the view can listen for message types and the view model can send messages to every listening receiver.

Usage

The following code registers the TextMessage message for the current object. In a Windows Phone application, this should be called in the App class in the method Application_Launching() and Application_Activated().

Messenger.Default.Register<TextMessage>(
	this, DefaultActions.GetTextMessageAction());

If you don't register a listener with a receiver object, the listener can only be unregistered with its delegate object.

The send a message to all registered listeners, use the following code:

var result = await Messenger.Default.SendAsync(new TextMessage("text"));

// or as extension method which sends using the default messenger: 
var result = await new TextMessage("text").SendAsync();

The following code will unregister all messages from the given object. In Windows Phone applications, this should be called in the App class in the methods Application_Closing() and Application_Deactivated().

Messenger.Default.Unregister<TextMessage>(this);

A message object should be immutable. Use the CallbackMessage class for messages with a result.