由于您正在使用 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;
}
}
}
}
并为在SubmitButonCommand
在 LogInViewModel (例如)发送关闭消息:
private RelayCommand _submitButonCommand;
public RelayCommand SubmitButonCommand
{
get
{
return _closeWindowCommand
?? (_closeWindowCommand = new RelayCommand(
() => Messenger.Default.Send(new NotificationMessage("CloseWindow"))));
}
}
并使用相同的方法在之间发送对象LoginViewModel
然后OtherWindowViewModel
例外的是这次您需要发送对象而不仅仅是NotificationMessage
:
在登录视图模型中:
Messenger.Default.Send<YourObjectType>(new YourObjectType(), "Message");
并在中接收该对象OtherWindowViewModel
:
Messenger.Default.Register<YourObjectType>(this, "Message", (yourObjectType) =>
//use it
);