如何在登录后关闭DialogWIndow并显示主窗口?

时间:2012-10-12 10:27:34

标签: wpf xaml

我有一个登录窗口和一个主窗口。现在,我想在成功登录后关闭登录窗口,然后我的主窗口应该打开。但到目前为止,我正在打开两扇窗户,这让我很恼火。

我在app.xaml的代码中尝试了下面的代码,但它关闭了整个应用程序......

DataRepository repository = new DataRepository();
ViewModelPassword viewModelPassword = new ViewModelPassword(repository);

passwordDialog passwordDialog = new PasswordDialog();
passwordDialog.DataContext = viewModelPassword;

viewModelPassword.RequestClose += (s, ee) => passwordDialog.Close();
passwordDialog.ShowDialog();

Mainviewmodel viewModel = new Mainviewmodel (repository, viewModelPassword.Login);
MainWindow window = new MainWindow();

window.DataContext = viewModel;
window.Show();

base.OnStartup(e);

登录命令启动成功登录后,我想显示主窗口。

1 个答案:

答案 0 :(得分:2)

在运行启动代码之前,您正在显示两个Windows,因此在应用程序启动时,两个窗口都会显示。

以下是我通常用于此场景的代码:

protected override void OnStartup(StartupEventArgs e)
{
    // Run startup code first
    base.OnStartup(e); 

    // Create Login Window and Show it
    var login = new LoginDialog();
    var loginVm = new LoginViewModel();

    login.DataContext = loginVm;
    login.ShowDialog();

    // If login window didn't return true (login failed), exit application
    if (!login.DialogResult.GetValueOrDefault())
    {
        Environment.Exit(0);
    }

    // Providing we have a successful login, start main application window
    var app = new ShellView();
    var context = new ShellViewModel(loginVm.CurrentUser);
    app.DataContext = context;
    app.Show();
}