如何知道窗口关闭是已完成还是被取消?

3

WPF应用程序。 Window1可以打开WindowA.Show(),WindowB.Show(),WindowC.Show()

当我们关闭Window1时,我们希望同时关闭所有打开的窗口(A、B和C)。

Window1_Closing事件中,我们调用

WindowA.Close();
WindowB.Close();
WindowC.Close();

在任何一个窗口关闭时,都可以调用Cancel = true,这样WindowA(或B或C)就不会关闭。 然后我们不想关闭父窗口Window1。 如何在Window1_Closing中知道任何一个子窗口是否被取消(而不是关闭)?

那个 Window 是一个窗体吗? - Joel Legaspi Enriquez
1
你能不能给你的子窗口WindowA等添加一个属性呢?然后在关闭时,根据是否取消了关闭操作,将其设置为true或false。在你的应用程序窗口中,你可以检查该属性并在必要时取消操作。 - Serge Desmedt
你的应用程序中还有其他窗口吗?如果没有,在 Window1 关闭时,你也可以使用 Exit() 函数关闭整个应用程序,这将关闭其所有子窗口(A、B、C)。 - Casper
@Serge - 我先尝试了这篇帖子。建议的解决方案没有起作用。IsLoaded 一直是 true,所以我永远无法关闭窗口... - st_stefanov
@st_stefanov这就是为什么在评论中有人说:所以我最终使用了自己的实例变量,并以不需要同步的方式访问它(在OnClosed方法的开头设置isClosed = true,然后稍后再次读取它)。 - Serge Desmedt
显示剩余7条评论
1个回答

2
  1. Window.Closed event is fired after the window is closed. Either move your logic to eventhandler of Closed event, or use the event to send some flag:

    bool isClosed = false;
    WindowA.Closed += delegate { isClosed = true; };
    WindowA.Close();
    
    if (isClosed) { 
    }
    
  2. Application.Current.Windows is collection of currently opened windows:

    WindowA.Close();
    bool isClosed = !Application.Current.Windows.OfType<Window>().Contains(WindowA);
    

@Serge,我实现了你建议的解决方案,它也很好地工作了。谢谢。 - st_stefanov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接