简体   繁体   中英

Closing all windows and opening another one in WPF

so I have three windows in my WPF app, a login window, a main window and a confirm log out window. the confirm log out window has two buttons yes and no, when the user clicks the no button the window gets closed, but when the user clicks the yes button I want the main window and the confirm log out window to get closed and the log in window gets shown.

the problem is that the code works fine but when I close the logout confirmation window the main window is not closed with it

here's my code

    private void NoButton_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
    }

    private void YesButton_Click(object sender, RoutedEventArgs e)
    { 
        try
        {
            Properties.Settings.Default.UserName = null;
            Properties.Settings.Default.UserPassword = null;
            Properties.Settings.Default.Save();
        }
        catch (Exception exp)
        {
            Console.WriteLine(exp);
        }

        this.Hide();
        Window loginWindow = new Login();
        loginWindow.Show();
        this.Close();
    }

So the answer to this question was that i needed to reach the main window that is calling the log out confirm window to pop up and close it with it, here's the code

private void YesButton_Click(object sender, RoutedEventArgs e)
{ 
    try
    {
       Properties.Settings.Default.UserName = null;
       Properties.Settings.Default.UserPassword = null;
       Properties.Settings.Default.Save();
    }
    catch (Exception exp)
    {
       Console.WriteLine(exp);
    }

    this.Hide();
    Window mainWindow = Application.Current.MainWindow;
    mainWindow.Close();
    Window loginWindow = new Login();
    loginWindow.ShowDialog();
    this.Close();
}

keep in mind that you need to set the Application.Current.MainWindow value in the main window constructor so it doesn't return null sometimes

public MainWindow()
    {
        Application.Current.MainWindow = this;
    }

Don't do the logout from the logout window. Just use the logout window to get a response from the user, then perform the logout (or not) from within the main window.

From the mainwindow:

if(logoutWindow.ShowDialog() == true)
{
    try
    {
       Properties.Settings.Default.UserName = null;
       Properties.Settings.Default.UserPassword = null;
       Properties.Settings.Default.Save();
    }
    catch (Exception exp)
    {
       Console.WriteLine(exp);
    }
    ...
    //open login, close this etc.
}

In the logout dialog

private void YesButton_Click(object sender, RoutedEventArgs e)
{ 
    DialogResult = true;
}

private void NoButton_Click(object sender, RoutedEventArgs e)
{ 
    DialogResult = false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM