我有一个带按钮的wpf应用程序,它会打开一个新窗口,我要在其中确定一些设置。请参阅以下代码:
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();
}
}
但是,当我关闭SettingsWindow并想从MainWindow重新打开它时,整个应用程序将冻结。 我认为该对象将在关闭时被破坏,从而在if子句中重新初始化。
我是否必须在SettingsWindow的关闭例程中进行覆盖,还是忽略其他内容?
答案 0 :(得分:3)
您将要跟踪SettingsWindow是否已关闭。否则,您将重新显示一个可能已关闭并已废弃的窗口。关闭窗口不会删除您对此的引用。
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();
}
}