1

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?

5
  • Closing the window does not destroy the object, you need to handle the window close event and dispose of the object there, or use a modal dialog (.ShowDialog()) instead of just another window. Commented Sep 4, 2018 at 15:39
  • If it doesn't destroy the object, the if clause should be passed and SettingsWindow.Show(); should display the window again shouldn' it? Commented Sep 4, 2018 at 15:41
  • 1
    The code you posted won't cause the issues you are talking about, it must be something in the settings window that happens to cause the program to "lock up". When you hit the pause button in the debugger, what line does it break on? Commented Sep 4, 2018 at 15:42
  • I think the issue is that this.SettingsWindow won't be null. Closing the window will not clear that reference. So you are likely trying to re-show a window that is already closed\disposed. Commented Sep 4, 2018 at 15:44
  • @RonBeyer No there is nothing done in the settingsWindow so far. Just a simple prototype. Commented Sep 4, 2018 at 15:52

1 Answer 1

6

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(); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I have searched for. Nice answer. Also thanks for the explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.