h0ch5tr4355
h0ch5tr4355

Reputation: 2192

How can I close and reopen a window in wpf?

I have a wpf application with a button, which opens a new Window, where I want to determine some settings. See following code:

public partial class MainWindow : Window
{
    private SettingsWindow SettingsWindow;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void settings_Click(object sender, RoutedEventArgs e)
    {
        if (this.SettingsWindow == null)
        {
            SettingsWindow = new SettingsWindow(); // No reentrace here !!!
        }
        SettingsWindow.Show();
        SettingsWindow.Focus();
    }
}

However, when I close the SettingsWindow and want to reopen it from the MainWindow, the whole application freezes. I thought the object would be destroyed at closing and thus initialized newly inside the if-clause.

Do I have to do an override in the SettingsWindow's close routine or did I disregard something else?

Upvotes: 1

Views: 3022

Answers (1)

Brian Rudolph
Brian Rudolph

Reputation: 6328

You will want to track if the SettingsWindow has been closed. Otherwise you are re-showing a window that has likely been closed and is disposed. Closing the window will not remove your reference to it.

public class SettingsWindow : Window
{
    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
        this.IsClosed = true;
    }

    public bool IsClosed { get; private set; }
}

public partial class MainWindow : Window
{
    private SettingsWindow settingsWindow;
    private void settings_Click(object sender, RoutedEventArgs e)
    {
        if (this.settingsWindow == null || this.settingsWindow.IsClosed) 
        {
            this.settingsWindow = new SettingsWindow();
        }
        this.settingsWindow.Show();
        this.settingsWindow.Focus();
    }
}

Upvotes: 6

Related Questions