IMHO, it is better to use NotificationMessageAction<T> , since it is cut for this task.
On the sender side:
var msg = new NotificationMessageAction<MessageBoxResult>(this, "GetPassword", (r) => { if (r == MessageBoxResult.OK) { // do stuff } }); Messenger.Default.Send(msg);
And on the receiver side:
Messenger.Default.Register<NotificationMessageAction<MessageBoxResult>>(this, (m) => { if (m.Notification == "GetPassword") { var dlg = new PasswordDialog(); var result = dlg.ShowDialog(); m.Execute(result); } });
I believe this approach is cleaner since it does not create an unnecessary dependency on View to ViewModel (although this path is not so bad). For better readability, consider subclassing for NodificationMessageAction<MessageResult> . I.e.
public class ShowPasswordMessage : NotificationMessageAction<MessageBoxResult> { public ShowPasswordMessage(object Sender, Action<MessageBoxResult> callback) : base(sender, "GetPassword", callback) { } }
Then sender
var msg = new ShowPasswordMessage(this, (r) => { if (r == MessageBoxResult.OK) { // do stuff } }); Messenger.Default.Send(msg);
and receiver side
Messenger.Default.Register<ShowPasswordMessage>(this, (m) => { var dlg = new PasswordDialog(); var result = dlg.ShowDialog(); m.Execute(result); });
It becomes much clearer.
And verry important, unregister the recipient, as otherwise you could create a memory leak.
Axelckenberger
source share