如何使用 MVVM Light Toolkit 打开新窗口 [英] How to open a new window using MVVM Light Toolkit

查看:53
本文介绍了如何使用 MVVM Light Toolkit 打开新窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 WPF 应用程序中使用 MVVM Light 工具包.我想知道从现有窗口打开新窗口的最佳方法是什么.我有这个 MainViewModel,它负责我的应用程序的 MainWindow.现在在 MainView 中,单击按钮,我想在它上面打开第二个窗口.我已将 RelayCommmand 绑定到 ButtonCommand.在RelayCommand 的方法中,我可以创建一个新的窗口对象并简单地调用Show(),如下所示:

I am using MVVM Light toolkit in my WPF application. I would like to know what is the best approach for opening a new window from an existing window. I have got this MainViewModel, which is responsible for MainWindow of my application. Now in the MainView, on a button click, I would like to open a second window on top of it. I have got RelayCommmand binded to the Button's Command. In the RelayCommand's method, I can create a new window object and simply call Show(), something like this:

var view2 = new view2()
view2.Show()

但我不认为 ViewModel 应该负责创建新的 view2 对象.我已经阅读了这篇文章 WPF MVVM 从 VIEW MODEL 获取父级 where Bugnion建议将消息​​从 viewmodel1 传递给 view1,然后 view1 应该创建新的 view2.但我不确定他将消息传递给 view1 究竟是什么意思?view1 应该如何处理消息?在它背后的代码还是什么?

but I don't think the ViewModel should be responsible for creating the new view2 object. I have read this post WPF MVVM Get Parent from VIEW MODEL where Bugnion has suggested to pass message to the view1 from the viewmodel1 and then view1 should create the new view2. But I am not sure what does he actually mean by passing the message to the view1? How should the view1 handle the message? In it's code behind or what?

问候,纳比尔

推荐答案

将消息从 ViewModel1 传递到 View1 意味着使用 MVVM Light Toolkit 中的消息传递功能.

Passing a message from ViewModel1 to View1 means to use the messaging capabilities in the MVVM Light Toolkit.

例如,您的 ViewModel1 可能有一个名为 ShowView2Command 的命令,然后它会发送一条消息来显示视图.

For example, your ViewModel1 could have a command called ShowView2Command, then it would send a message to display the view.

public class ViewModel1 : ViewModelBase
{
    public RelayCommand ShowView2Command { private set; get; }

    public ViewModel1() : base()
    {
        ShowView2Command = new RelayCommand(ShowView2CommandExecute);
    }

    public void ShowView2CommandExecute()
    {
        Messenger.Default.Send(new NotificationMessage("ShowView2"));
    }
}

View1 会在其背后的代码中注册接收消息,并在收到正确消息时显示 View2.

View1 would register to receive messages in its code behind and display View2 when it receives the correct message.

public partial class View1 : UserControl
{
    public View1()
    {
        InitializeComponent();
        Messenger.Default.Register<NotificationMessage>(this, NotificationMessageReceived);
    }

    private void NotificationMessageReceived(NotificationMessage msg)
    {
        if (msg.Notification == "ShowView2")
        {
            var view2 = new view2();
            view2.Show();
        }
    }
}

这篇关于如何使用 MVVM Light Toolkit 打开新窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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