33

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.

Jason D
  • 2,634
  • 6
  • 33
  • 67

2 Answers2

64

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;
}
heltonbiker
  • 26,657
  • 28
  • 137
  • 252
Aaron McIver
  • 24,527
  • 5
  • 59
  • 88
  • 1
    I prefer to use the type of the view in the message instead of a part of the name because it will be changed when renaming the page or moving it to another namespace/folder – Emond Jun 08 '13 at 06:33
  • Thanks, this was exactly what I was looking for. I think I'm also going to pass types rather than strings, intellisense alone makes life that much more enjoyable. – Billy Jake O'Connor Sep 14 '16 at 17:52
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.

Ehsan
  • 767
  • 7
  • 18