1

当我打开一个新的子窗体时,我有如下 C# WinForms 代码来关闭所有子窗体:

private void CloseAllActiveForms(Form[] MdiChildren)
{
    Form[] childArray = MdiChildren;
    foreach (Form childform in childArray)
    {
        childform.Close();
    }
}

如何在 WPF 窗口中使用?

我尝试了下面的代码,但它会关闭所有窗口,包括父窗口和活动窗口。

private void CloseAllWindows()
{
    for (int intCounter = App.Current.Windows.Count - 1; intCounter >= 0; intCounter--)
    {
        Application.Current.Windows[intCounter].Close();
    }
}

谢谢。

4

2 回答 2

5

据我所知,MDI 对 WPF 的支持是有限的,所以在创建伪子窗口时尝试使用 Tag 属性:

Window child = new Window();
child.Tag = "mdi_child";

然后,在你的循环中,像这样修改它:

foreach (Window win in App.Current.Windows)
{
    if (!win.IsFocused && win.Tag.ToString() == "mdi_child")
    {
        win.Close();
    }
}

请注意,要使上述解决方案起作用,所有窗口都必须具有 Tag 属性,否则将在win.Tag.ToString().

于 2012-06-05T02:57:03.897 回答
5

这是我在 WPF 中用来关闭程序的所有子窗口的方法,此代码位于主window.cs文件中,但您可以修改if(item!=this)以检查特定窗口:

foreach(Window item in App.Current.Windows)
{
    if(item!=this)
        item.Close();
}

No faffing around with sub-classes or more lists (especially as the code already has a list of windows associated with it.)

If you wanted to selectively close windows then you could always modify the if statement to use a variable on the window class or check one of the pre-existing variables (such as a the class of the parent window) on the base window class.

于 2015-09-19T04:39:13.000 回答