如何使用mvvm-light Messenger接收DialogResult [英] How to receive DialogResult using mvvm-light Messenger

查看:383
本文介绍了如何使用mvvm-light Messenger接收DialogResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 mvvm-light Messenger功能在视图中打开由视图模型中的命令触发的自定义确认密码对话框.

I'm trying to use the mvvm-light messenger capability to open a custom confirm password dialog in my view, triggered by a command in my viewmodel.

我想我了解Messenger.Default.RegisterMessenger.Default.Send的用法.

但是如何将对话框结果恢复到我的视图模型中?

对我来说,发送似乎是一条单向路...

To me the sending seems to be a one way street...

有人可以用一个小的C#/WPF代码示例来帮助初学者吗?

Could someone help a beginner with a small C#/WPF code sample?

感谢您的帮助

推荐答案

恕我直言,最好使用NotificationMessageAction<T>,因为它是为此任务切出的.

IMHO it is better to use the NotificationMessageAction<T> as it is cut out for this task.

在发送方:

var msg = new NotificationMessageAction<MessageBoxResult>(this, "GetPassword", (r) =>
{
    if (r == MessageBoxResult.OK)
    {
        // do stuff
    }
});

Messenger.Default.Send(msg);

在接收方:

Messenger.Default.Register<NotificationMessageAction<MessageBoxResult>>(this, (m) =>
{
    if (m.Notification == "GetPassword") {
        var dlg = new PasswordDialog();
        var result = dlg.ShowDialog();
        m.Execute(result);
    }
});

我相信这种方法更干净,因为它不会在View到ViewModel之间创建不必要的依赖关系(尽管这种方式还算不错).为了提高可读性,请考虑对NodificationMessageAction<MessageResult>进行子分类.即

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)
    {

    }
}

然后是发件人

var msg = new ShowPasswordMessage(this, (r) =>
{
    if (r == MessageBoxResult.OK)
    {
        // do stuff
    }
});

Messenger.Default.Send(msg);

和接收方

Messenger.Default.Register<ShowPasswordMessage>(this, (m) =>
{
    var dlg = new PasswordDialog();
    var result = dlg.ShowDialog();
    m.Execute(result);
});

变得更加清晰

非常重要,请取消注册收件人,否则可能会造成内存泄漏.

And verry important unregister the recipient as else you might create a memory leak.

这篇关于如何使用mvvm-light Messenger接收DialogResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆