MVVM Light WPF 打开新窗口

3

我是MVVM的新手,正在使用MVVM Light学习。

我有一个WPF应用程序,其中包含一个登录窗口。当用户输入正确的凭据时,登录窗口应关闭并打开一个新的MainWindow。登录部分已经工作了,但是如何打开一个新窗口并关闭当前窗口(login.xaml)呢?

此外,必须向这个新的MainWindow提供一些参数。

有人能为我指明正确的方向或提供一些信息吗?


可能是重复的问题:如何使用MVVM Light Toolkit打开新窗口 - Patrick Quirk
这是我通常用来关闭登录窗口并显示主应用程序窗口的代码:如何在登录后关闭对话框窗口并显示主窗口? - Rachel
1个回答

7

由于您正在使用MvvmLight,因此可以使用Messenger类(mvvmlight中的助手类),该类用于在ViewModel之间以及ViewModel和View之间发送消息(通知+对象)。在您的情况下,当登录成功时,需要在LoginViewModel中发送一条消息(可能在提交按钮的处理程序中),以关闭LoginWindow并显示其他窗口:

LogInWindow代码后台

public partial class LogInWindow: Window
{       
    public LogInWindow()
    {
        InitializeComponent();
        Closing += (s, e) => ViewModelLocator.Cleanup();

        Messenger.Default.Register<NotificationMessage>(this, (message) =>
        {
            switch (message.Notification)
            {
                case "CloseWindow":
                    Messenger.Default.Send(new NotificationMessage("NewCourse"));
                    var otherWindow= new OtherWindowView();
                    otherWindow.Show();   
                    this.Close();            
                    break;
            } 
        }
    }
 }

在LogInViewModel中的SubmitButonCommand(例如)中发送关闭消息:
private RelayCommand _submitButonCommand;
public RelayCommand SubmitButonCommand
{
    get
    {
        return _closeWindowCommand
            ?? (_closeWindowCommand = new RelayCommand(
            () => Messenger.Default.Send(new NotificationMessage("CloseWindow"))));
    }
}

使用相同的方法在LoginViewModelOtherWindowViewModel之间发送对象,不同之处在于这次您需要发送对象而不仅仅是NotificationMessage: 在LoginViewModel中:

 Messenger.Default.Send<YourObjectType>(new YourObjectType(), "Message");

并在 OtherWindowViewModel 中接收该对象:

Messenger.Default.Register<YourObjectType>(this, "Message", (yourObjectType) =>
                                                           //use it 
                                                             );

谢谢Joseph。我已经明白了,包括有和没有对象的情况! - Kaizer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接