首页 > 解决方案 > C# WPF Window.Closed 只触发一次

问题描述

在我的 WPF 项目中,我有一个事件subWindow.Closed,它在关闭时基本上会更新我的主窗口。此事件仅适用于原始事件,subWindow因此即使我编写this.subWindow = new SubWindow();它也不会再次触发,如果我再次打开和关闭子窗口。简单的答案似乎是取消关闭使用subWindow.Closing并隐藏它,但如果可以的话,我还想使主窗口不可用subWindow.ShowDialog,这不适用于隐藏子窗口。

现在我的代码看起来像这样:

public SubWindow subWindow = new SubWindow();

public MainWindow()
{
  subWindow.Closed += (s, EventArgs) =>
  {
    //main window update code
    subWindow = new SubWindow(); //this lets me ShowDialog but wont get caught by the event handler
  }
}

public void EditButton_Click(object sender, RoutedEventArgs e)
{
  this.subWindow.ShowDialog();
  //setting subWindow here would let me always ShowDialog but the event only triggers once
}

标签: c#wpf

解决方案


从构造函数中删除所有内容MainWindow并将所有内容放入Button.Click事件处理程序:

public void EditButton_Click(object sender, RoutedEventArgs e)
{
    subWindow = new SubWindow();
    subWindow.Closed += (s, EventArgs) =>
    {
        //main window update code
    };
    this.subWindow.ShowDialog();
}

推荐阅读