Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a login window and a main window. Now, I want to close the login window after a successful login and my main window should then open. But so far, I am getting both windows opening which is irritating me.

I have tried the code below in the code behind of app.xaml but it closes the whole application...

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);

After the login command has initiated a successful login, I want to display the main window.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

You are showing both Windows before even running the startup code, so on application startup both windows are showing.

Here's the code I typically use for this scenario:

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...