Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 796
Jason D Avatar asked Jun 07 '13 22:06

Jason D


People also ask

What is Mvvm messaging?

MVVM Light Messenger is a class that allows exchange messages between objects. Messenger class is mainly used for sending messages between viewmodels. Messenger class decreases coupling between viewmodels. Every viewmodel can communicate with another viewmodel without any association between them.

What is MVVM Light?

MVVM is a pattern on how to structure your UI and data and business logic. MVVM light is a lightweight framework that supports you in implementing the pattern.

What is MVVM Light Toolkit?

The MVVM Light Toolkit is a set of components helping people to get started in the Model-View-ViewModel pattern in Silverlight, WPF, Windows Phone, Windows 10 UWP, Xamarin. Android, Xamarin. iOS, Xamarin. Forms. It is a light and pragmatic framework that allows you to pick which components you want to use.


2 Answers

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; } 
like image 132
Aaron McIver Avatar answered Sep 20 '22 19:09

Aaron McIver


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.

like image 25
Ehsan Avatar answered Sep 21 '22 19:09

Ehsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!