What is the proper way to use tokens with the Mess

2019-06-25 12:13发布

问题:

I am using version 3.0.3.19 of the MVVM Light Toolkit.

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

Messages can now be sent through the Messenger with a token.

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

  • To receive a message with token, use the methods Register(object recipient, object token, Action action) or Register(object recipient, object token, bool receiveDerivedMessagesToo, Action 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 with no token at all.


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

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

Along with the following 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?

回答1:

My ViewModelLocator was initializing ViewModel A before ViewModel B. In other words, the message was being sent properly by ViewModel A, but ViewModel B was not yet around to actually receive it.

I changed the order of initialization in the ViewModelLocator and the problem was solved. Also, verified that the Messenger worked with tokens of other types besides String.



标签: mvvm-light