I am using MVVM Light for my current WPF project and I wonder when I should use MVVM Light's Messaging over WPF Events.
WPF Event:
MyControl.xaml
<ListView SelectionChanged="ListView_OnSelectionChanged" />
MyControl.cs
private MyViewModel ViewModel
{
get { return this.DataContext as MyViewModel; }
}
private void ListView_OnSelectionChanged( object sender, SelectionChangedEventArgs e )
{
this.ViewModel.ListViewSelectionChanged( ( (ListView) sender ).SelectedItems );
}
MVVM Light Messaging:
MyControl.cs
private void ListView_OnSelectionChanged( object sender, SelectionChangedEventArgs e )
{
Messenger.Default.Send( new ListViewSelectionMessage {SelectedItems = ((ListView)sender).SelectedItems} );
}
ListViewSelectionMessage.cs
public class ListViewSelectionMessage
{
public IList SelectedItems { get; set; }
}
MyViewModel
public class MyViewModel
{
MyViewModel()
{
Messenger.Default.Register<ListViewSelectionMessage>(this, this.ListViewSelectionChaged);
}
private void ListViewSelectionChaged( ListViewSelectionMessage message )
{
// ...
}
}
Because using a Messanger everything is decoupled pretty easily I am tempted to use a Messanger everywhere. Is there something wrong using a Messanger instead of Events? Or does this produce problems I am not aware of. Thanks!
Generally messages in any MVVM frameworks (Prism , MVVM Light) are great way to communicate between loosely coupled components in applications with plugin architecture, because you can send message from one module to another by contract declared in shared library. And it's ok to use it while you develop your application alone or in small team highly skilled programmers.
Otherwise there is a major drawback: it's extremely hard to refactor and debug, because you can't just click on message and "find usages" you need first to go to contract (Interface) than "find usages", and then visually find places with Subscribe/Register directive. Moreover usually developers forget to unsubscribe from messages so you will face problem while message sent from one module and intended to be processed in same module will be mistakenly processed in other modules, so it will cause unexpected behavior and create so many painful bugs.
All above are based on my personal experience so results may differ. Just be careful with messages and it will serve you well. Also in my opinion messages as replacement for events are a little bit overhead/overengineering because you don't really need it while you have tightly coupled components.