I use MVVM Light toolkit for my WPF applications at work. I’ve always only used it’s basic features: SimpleIoC and the ViewModelBase. It’s a very powerful and framework. However, I’ve been wanting to explore more feature of the framework.
When I start with a new technology, I always create simple and fully-working examples for reference… and for other coworkers. Here is an example of using the messaging aggregator feature of MVVM Light. Normally, I use the Command framework in WPF. However, I was curious how the MVVM Light Toolkit Messaging is used. It’s a fairly powerful way for components to publish and subscribe to messages without the need for tight coupling.
The complete solution can be found in my GitHub repository named MvvmLightMessaging.
Setting up a basic MVVM Light WPF application is described in detail elsewhere. Please see the GalaSoft site for references.
Messaging requires three steps
- A message to send
- A sending event
- A receiving property
In my example I create a ButtonMessage class
namespace MvvmLightMessenging.Messages { public class ButtonMessage { public string ButtonText { get; set; } } }
Next, my view has a button with a Click event. That event sends a message to the messaging system.
private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { Messenger.Default.Send<ButtonMessage>(new ButtonMessage(){ButtonText = "Button Pressed!"}); }
My MainViewModel, during instantiation, wires it’s self to listen for any ButtonMessage events
Messenger.Default.Register<ButtonMessage>(this, (message) => { this.Data = message.ButtonText; });
Thus, when the button is clicked, a ButtonMessage is sent and a dependant property is updated.
This same effect can be accomplished with the WPF Command strategy. However, this is nice to have multiple recepients for the same event in a loosely coupled manner.
I hope you find this simple example useful.