问题
I see in the MVVM-Light package that I can send messages with tokens- what I need to do is send an object, with a message attached to that object- like Add, Edit, Delete whatever.
What is the best way to send and to recieve this message? I think for send its just: Messenger.Default.Send(myObject, ActionEnum.DELETE);
But in the receive: Messenger.Default.Register(this, ????, HandleMyMessage);
What is the correct syntax?
Thanks!
回答1:
Here is a quick section of code for both the send and the register. Your Notification is the message that instructs the receiver what the intention was. The Content is the item you wanted to send, and you can further identify who sent the message, and even what object this message was intended for with the sender and the target.
Messenger.Default.Send<NotificationMessage<Job>>(
new NotificationMessage<Job>(this, myJob, "Add")
);
Messenger.Default.Register<NotificationMessage<Job>>(
this, nm =>
{
// this might be a good idea if you have multiple recipients.
if (nm.Target != null &&
nm.Target != this)
return;
// This is also an option
if (nm.Sender != null &&
nm.Sender != expectedFrom) // expectedFrom is the object whose code called Send
return;
// Processing the Message
switch(nm.Notification)
{
case "Add":
Job receivedJob = nm.Content;
// Do something with receivedJob
break;
case "Delete":
Job receivedJob = nm.Content;
// Do something with receivedJob
break;
}
});
回答2:
Just as an addition: The token is not meant to identify a task (notification), but rather a receiver. The receiver(s) who register(s) with the same token as the sender will get the message, while all other receivers won't get it.
For what you want to do, I use the optional NotificationMessage type included in the toolkit. It has an additional string property (Notification) that you can set to anything you want. I use this to "give orders" to the receiver.
Cheers, Laurent
来源:https://stackoverflow.com/questions/3393286/how-to-use-mvvm-light-with-tokens