Using the message broker to decouple components

To decouple components, in order to improve testability and code clearness, you can use our implementation of the Mediator pattern (aka Message Broker)

This is ideal in MVVM scenario in WPF/SL/WP7.

To use it, you have to:
  • Define a message class that will be send from you components to all registered ones:

public class ActionMessage
{
	private readonly string action;

	public ActionMessage(string action)
	{
		this.action = action;
	}

	public string Action
	{
		get { return action; }
	}
}
  • Register one or more listener for your message class, that will define an action to execute when a message of that particular type will be sent, calling the Register message.
In a MVVM scenario, this is usually done in the View code (Window or Controls).

public partial class MainWindow : Window
{
	public MainWindow()
	{
		InitializeComponent();

		MessageBroker.Register<ActionMessage>(ShowAction);
	}

	private void ShowAction(ActionMessage o)
	{
		textBox1.Text = o.Action;
	}
}
  • Send the message in your code calling the Send method.
In a MVVM scenario, this is usually done in the ViewModel code, maybe in response to a Command.
In the snippet provided, however, it's used in response to button click events of a user control.

	public partial class TextToolBar : UserControl
{
	public TextToolBar()
	{
		InitializeComponent();
	}

	private void BoldButtonClick(object sender, System.Windows.RoutedEventArgs e)
	{
		MessageBroker.Send(new ActionMessage("bold"));
	}

	private void ItalicButtonClick(object sender, System.Windows.RoutedEventArgs e)
	{
		MessageBroker.Send(new ActionMessage("italic"));
	}

	private void UnderlineButtonClick(object sender, System.Windows.RoutedEventArgs e)
	{
		MessageBroker.Send(new ActionMessage("underline"));
	}
}

Last edited May 25, 2011 at 9:01 PM by DocMartin, version 2

Comments

No comments yet.