简体   繁体   English

Control.Controls属性是否以递归方式返回嵌套控件?

[英]Does Control.Controls property return recursively nested controls?

The MSDN documentation for System.Windows.Forms.Control.Controls property (for example, here ) states: System.Windows.Forms.Control.Controls属性的MSDN文档(例如, 此处 )指出:

Use the Controls property to iterate through all controls of a form, including nested controls . 使用Controls属性迭代窗体的所有控件, 包括嵌套控件

I'm at a loss as for what does "nested controls" properly mean here. 我不知道“嵌套控件”在这里的含义是什么。
To illustrate an issue, I made a form, consisting of: 为了说明问题,我做了一个表格,包括:

  • a button 一个按钮
  • a ListBox 一个ListBox
  • a groupbox with a button inside. 一个内部有按钮的组合框。

The code 编码

MessageBox.Show(Controls.Count.ToString());

yields the answer 3. Based on my understanding of the docs, I have assumed it would provide 4 instead (counting the button inside the groupbox). 得出答案3.根据我对文档的理解,我假设它将提供4(计算组框内的按钮)。 The same behavior is observed if the groupbox is replaced by the panel. 如果组框由面板替换,则会观察到相同的行为。

What does the aforementioned phrase about nested controls actually mean? 关于嵌套控件的上述短语实际上意味着什么?

Control.Controls is a collection of that control's immediate children. Control.Controls是该控件的直接子项的集合。 Therefore your form's Controls collection will have 3 controls. 因此,您的表单的Controls集合将具有3个控件。 And your GroupBox's Controls collection will have 1 control (the button). 而你的GroupBox的Controls系列将有1个控件(按钮)。

I'm not really sure what that comment in the documentation was getting at, aside from perhaps (although not so eloquently) hinting that you can use this property recursively to get at all nested controls. 我不太确定文档中的注释是什么,除了(尽管不是那么雄辩)暗示你可以递归地使用这个属性来获取所有嵌套控件。 For example: 例如:

static IEnumerable<Control> GetAllDescendantControls(this Control c)
{
    return c.Controls.Cast<Control>()
        .Concat(c.Controls.SelectMany(x => x.GetAllDescendantControls()));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM