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?
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);