tenminmail
tenminmail

Reputation: 83

Closing wpf window before opening a new one

I have a button that opens a WPF window which shows some calculation.

public void SomeButton_Click(object sender, RoutedEventArgs e)
{
    Window1 win2 = new Window1();
    win2.Show();
    win2.Topmost = true;
}

I have a problem that if I change values in the program and press the button again, I have two open windows. Is there a way that I can close win1 before opening the new version of win2? I tried with win2.Close(), but since win2 is not known before the application creates it won't obviously work.

Thanks.

Upvotes: 0

Views: 121

Answers (1)

mm8
mm8

Reputation: 169390

You could store a reference to the window in a variable in your class:

private Window2 win2;
public void SomeButton_Click(object sender, RoutedEventArgs e)
{
    win2?.Close();
    win2 = new Window2();
    win2.Show();
    win2.Topmost = true;
}

This will close any previous instance of Window2 that you have created and opened in the click event handler before you open a new window.

Upvotes: 1

Related Questions