1
votes

I am using mvvm light on my project. For communication between view, I am using GalaSoft.MvvmLight.Messaging.Messenger but it does not work as expected.
The code below:
Register a messenger

GalaMessenger.Default.Register<ServerNewMessenger>(ServiceLocator.Current.GetInstance<ServerNewViewModel>(), (msg) =>
            {
                Debug.Write("Click");
            });

Send messenger to receiver

Messenger.Default.Send<ServerNewMessenger>(newItem, ServiceLocator.Current.GetInstance<ServerNewViewModel>());

I never receive the message. But when I remove the recipient by the send method:

Messenger.Default.Send<ServerNewMessenger>(newItem);  

Then it works fine. Why?

1
It's very important to initialize class/function which holds Default.Register before the Default.Send. It can be your problem. Check it. - A191919
Yes I did execute Default.Register before Default.Send. - softshipper
Does the call to GetInstance return a different instance on each call? - Patrick Quirk
Yes, I validate with the method GetHashCode() and it shows me the same code, that means it points to the same object. - softshipper

1 Answers

2
votes

You're confused about the overloads of Register and Send. In your second sample, you're using this overload of Send:

void Send<TMessage>(TMessage message, object token);

Since you're sending a message with a particular token, only those that called Register with that same token will receive the message. In your first example, you're using this overload of Register:

void Register<TMessage>(object recipient, Action<TMessage> action);

You are specifying no token, so your object will not receive it.

If really do you want to send this message to just your ServerNewViewModel, use a unique token like a GUID or some string that you make up:

string token = "YourServerViewModelToken";
var serverNewViewModel = ServiceLocator.Current.GetInstance<ServerNewViewModel>();
GalaMessenger.Default.Register<ServerNewMessenger>(serverNewViewModel, token, (msg) =>
    {
        Debug.Write("Click");
    });

Then when you send it, use the same token:

string token = "YourServerViewModelToken";
Messenger.Default.Send<ServerNewMessenger>(newItem, token);