我在MVVM-Light包中看到,我可以发送带有令牌的消息-我需要做的是发送一个对象,并在该对象上附加一条消息-如添加、编辑、删除等。
发送和接收此消息的最佳方式是什么?我认为为了发送它: Messenger.Default.Send(myObject,ActionEnum.DELETE);
但在接收端: Messenger.Default.Register(this,?,HandleMyMessage);
正确的语法是什么?
谢谢!
发布于 2010-08-04 08:34:03
下面是用于发送和寄存器的代码的快速部分。你的通知就是告诉接收者你的意图是什么的信息。内容是您想要发送的项目,您可以进一步确定消息的发送者,甚至可以确定此消息针对发送者和目标的对象。
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;
}
});发布于 2010-08-07 01:55:01
只是作为补充:令牌不是用来标识任务(通知)的,而是用来标识接收者的。使用与发送者相同的令牌注册的接收者将收到消息,而所有其他接收者将不会收到该消息。
对于您想要做的事情,我使用了工具包中包含的可选NotificationMessage类型。它有一个额外的字符串属性(Notification),您可以将其设置为您想要的任何内容。我用它来向接收者“下达命令”。
干杯,Laurent
https://stackoverflow.com/questions/3393286
复制相似问题