Search code examples
c#wpfwindowshowdialog

WPF: Open and Close windows


I have two windows with WindowStyleset set a none, MainWindow and window1. I'd like to open window1 and close it when I click on a close button. Window1 is only used for configuration values.

I've tried with: In MainWindow I have a menu

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    Window1 secondWindow = new Window1();
    secondWindow.ShowDialog();
}

In Window1 close button code

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

When I click on close button, the app is closed. If I change ShowDialog() for Show() the app is closed. How can I do it? I only want to close window1 and stay in MainWindow?

Thank you!.


Solution

  • it's related to which of the Windows that you have is the Main window of the application try to set App.Current.MainWindow to your Main window like this

    private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            App.Current.MainWindow = this;
            Window1 secondWindow = new Window1();
            secondWindow.ShowDialog();
        }