在WPF中,我创建了一个单独的窗口来包含我的密码提示,该提示将在启动时显示。需要禁用MainWindow,仅在输入正确的密码时运行。我已经为我的MainWindow.xaml.cs做了以下事情:
public MainWindow()
{
InitializeComponent();
this.view_model = new MainViewModel();
this.DataContext = view_model;
LoginWindow login_window = new LoginWindow();
login_window.ShowDialog();
}
在LoginWindow中,输入密码,登录逻辑保持在按钮单击:
private void button_Login_Click(object sender, RoutedEventArgs e)
{
Tuple<bool, string> result = view_model.Login(this.textbox_password.Password);
if (result.Item1 == true)
{
// Login successful
}
else
{
MessageBox.Show(result.Item2, "Failed", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
我现在的问题是,如何通知MainWindowViewModel它可以继续使用其余的应用程序?有更好的方法吗?
答案 0 :(得分:1)
一种方法是挂钩MainWindow Initialized事件,在主窗口之前打开一个登录窗口。
private void MainWindow_Initialized(object sender, EventArgs e)
{
/*** Start Login ***/
new LoginWindow(this).ShowDialog();
}
然后在登录窗口中调用Login方法,此处为AttemptLogin
private void loginButton_Click(object sender, RoutedEventArgs e)
{
try
{
//Disable login button to avoid multiple login attempts
loginButton.IsEnabled = false;
m_mainform.AttemptLogin(UNtextBox.Text, PWpasswordBox.Password, otherID1, otherID2, this);
}
catch (Exception Ex)
{
loginButton.IsEnabled = true;
//Login Error - Report error
}
}
然后只有在验证了Attempt登录回调时才允许调用主要方法
private void LoginCheck(API.LoginResp resp, CustomAsyncStateContainer state)
{
try
{
//Process response
if (resp.header.errorCode != APIErrorEnum.OK)
{
//Login Failed - Show error if login failed
if (loginForm == null)
new LoginWindow(this).ShowDialog();
else
{
loginForm.Activate();
loginForm.loginButtonEnabled = true;
loginForm.PWpasswordBox.Password = null;
}
}
else
{
if (loginForm != null)
{
loginForm.Close();
//Continue with Main App
}
}
}
catch (Exception ex)
{
//Log error
}
}