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

查看:143
本文介绍了如何使用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从查看模型"获取父项,其中Bugnion建议从viewmodel1view1传递消息,然后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?

关于, 纳比尔(Nabeel)

Regards, Nabeel

推荐答案

将消息从ViewModel1传递到View1意味着使用

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天全站免登陆