MVVM Light Messenger - Sending and Registering Objects

Could somebody be kind enough to give me an example of how to Send and Register custom objects between classes using MVVM Light's Messenger or point me to a tutorial that covers this (preferably a concrete example)? I've been trying to use Messenger to pass an object in my project to another class but I've never been successful at it. I've looked online for examples but haven't found anything that shows me what I need. Thanks.


Solution 1:

Jesse Liberty of Microsoft has a great concrete walk through on how to make use of the messaging within MVVM Light. The premise is to create a class which will act as your message type, subscribe, then publish.

public class GoToPageMessage
{
   public string PageName { get; set; }
}

This will essentially send the message based on the above type/class...

private object GoToPage2()
{
   var msg = new GoToPageMessage() { PageName = "Page2" };
   Messenger.Default.Send<GoToPageMessage>( msg );
   return null;
}

Now you can register for the given message type, which is the same class defined above and provide the method which will get called when the message is received, in this instance ReceiveMessage.

Messenger.Default.Register<GoToPageMessage>
( 
     this, 
     ( action ) => ReceiveMessage( action ) 
);

private object ReceiveMessage( GoToPageMessage action )
{
   StringBuilder sb = new StringBuilder( "/Views/" );
   sb.Append( action.PageName );
   sb.Append( ".xaml" );
   NavigationService.Navigate( 
      new System.Uri( sb.ToString(), 
            System.UriKind.Relative ) );
   return null;
}

Solution 2:

I found THIS and THIS very useful. For the second reference use the Next Page button at the end to take you to examples they made.