【问题标题】:MVVM Light WPF open new windowMVVM Light WPF 打开新窗口
【发布时间】:2015-03-03 03:08:33
【问题描述】:

我是 MVVM 新手,并通过 MVVM Light 学习它。

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

还必须为这个新的 MainWindow 提供一些参数。

谁能告诉我正确的方向或提供一些信息?

【问题讨论】:

标签: wpf mvvm-light


【解决方案1】:

由于您使用的是 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;
            } 
        }
    }
 }

并在 SubmitButonCommandat LogInViewModel 中(例如)发送关闭消息:

private RelayCommand _submitButonCommand;
public RelayCommand SubmitButonCommand
{
    get
    {
        return _closeWindowCommand
            ?? (_closeWindowCommand = new RelayCommand(
            () => Messenger.Default.Send(new NotificationMessage("CloseWindow"))));
    }
}

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

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

并在OtherWindowViewModel 中接收该对象:

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

【讨论】:

  • 谢谢约瑟夫。我得到了它并没有一个对象!
猜你喜欢
  • 2014-11-08
  • 2011-03-24
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多