到目前为止,我已经创建了一个方法,用于检查用户是否在登录界面的文本框中输入了正确的用户名和密码,并将其绑定到两个属性。
我通过创建一个布尔方法来实现这一点,就像这样;
public bool CheckLogin()
{
var user = context.Users.Where(i => i.Username == this.Username).SingleOrDefault();
if (user == null)
{
MessageBox.Show("Unable to Login, incorrect credentials.");
return false;
}
else if (this.Username == user.Username || this.Password.ToString() == user.Password)
{
MessageBox.Show("Welcome " + user.Username + ", you have successfully logged in.");
return true;
}
else
{
MessageBox.Show("Unable to Login, incorrect credentials.");
return false;
}
}
public ICommand ShowLoginCommand
{
get
{
if (this.showLoginCommand == null)
{
this.showLoginCommand = new RelayCommand(this.LoginExecute, null);
}
return this.showLoginCommand;
}
}
private void LoginExecute()
{
this.CheckLogin();
}
我还有一个在xaml中绑定到按钮上的命令。
<Button Name="btnLogin" IsDefault="True" Content="Login"
Command="{Binding ShowLoginCommand}" />
当我输入用户名和密码时,它会执行相应的代码,无论是正确还是错误。但是当用户名和密码都正确时,我该如何从ViewModel中关闭这个窗口呢?
我之前尝试过使用一个“对话框模态”,但效果不太好。此外,在我的app.xaml中,我做了类似以下的操作,首先加载登录页面,然后一旦验证通过,再加载实际的应用程序。
private void ApplicationStart(object sender, StartupEventArgs e)
{
Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
var dialog = new UserView();
if (dialog.ShowDialog() == true)
{
var mainWindow = new MainWindow();
Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
Current.MainWindow = mainWindow;
mainWindow.Show();
}
else
{
MessageBox.Show("Unable to load application.", "Error", MessageBoxButton.OK);
Current.Shutdown(-1);
}
}
问题:我如何从ViewModel关闭登录窗口控件?
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
。 - Jacco DielemanWindow
对象传递给视图模型会破坏MVVM模式,因为这会强制你的vm知道它正在被查看的内容。如果视图是一个MDI界面中的停靠选项卡,那该怎么办呢?我认为正确的方法是传递某种实现了关闭方法的IUIHost接口,并让任何想要显示vm的视图来实现它。 - Crono