IMHO it is better to use the NotificationMessageAction<T>
as it is cut out 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 that this approach is cleaner as it does not create an unnecessary dependency from the View to the ViewModel (although this way round is not so bad). For better readability consider sub-classing the NodificationMessageAction<MessageResult>
. I.e.
public class ShowPasswordMessage : NotificationMessageAction<MessageBoxResult>
{
public ShowPasswordMessage(object Sender, Action<MessageBoxResult> callback)
: base(sender, "GetPassword", callback)
{
}
}
Then the 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);
});
becomes a lot clearer.
And verry important unregister the recipient as else you might create a memory leak.