What is the correct way to use tokens with the Messenger class?

I am using the MVVM Light Toolkit version 3.0.3.19.

From http://blog.galasoft.ch/archive/2010/03/16/whatrsquos-new-in-mvvm-light-v3.aspx :

Messages are now sent via Messenger using a token.

  • To send a message with a token, use the overload Send method (TMessage message, object token).

  • To receive a message with a token, use the Register methods (object receiver, object token, Action) or Register (object receiver, token object, bool receiveDerivedMessagesToo, action)

The token can be a simple value (int, string, etc.) or an instance of a class. The message is not delivered to recipients who registered with a different token or without a token at all.


According to the above documentation, I tried the following in ViewModel A:

Messenger.Default.Send(new NotificationMessage("message"), "token"); 

In the following figure in ViewModel B:

 Messenger.Default.Register<NotificationMessage>(this, "token", (msg) => Console.WriteLine(msg.Notification)); 

However, the callback is never executed. What am I doing wrong?

+4
source share
1 answer

My ViewModelLocator initialized ViewModel A before ViewModel B. In other words, the message was sent correctly by ViewModel A, but ViewModel B was not actually yet to receive it.

I changed the initialization order in ViewModelLocator and the problem was resolved. It is also verified that Messenger worked with tokens of other types besides String.

+3
source

All Articles