![](/img/trans.png)
[英]Determine at run time if a control allows other controls to be added to it at design time
[英]How to determine if a Control is a Container for other Controls
我正在編寫代碼以遍歷表單上的所有控件。 除了Form.Controls
集合不包含其他控件包含的控件外,這似乎很簡單。
好的,所以我嘗試測試以查看每個ctl is ContainerControl
,如果是,則遞歸地迭代該容器控件中的控件。
好的,但是事實證明GroupBox
控件不是從ContainerControl
派生的。 它直接來自Control
。
我的代碼是否有任何通用方法來確定給定控件是否包含其他控件? 我以為會有一個基本類型或接口可以做到這一點,但事實並非如此。
您可以使用Control.HasChildren
屬性:
如果此控件在其集合中包含子控件,則為true。
if (ctl.HasChildren)
{
// true, if ctl has controls in it
}
List<Control> AllFormsControl = new List<Control>();
public void InitContolList(Control nControl)
{
if (nControl.Controls.Count > 0)
{
foreach (Control item in nControl.Controls)
{
InitContolList(item);
AllFormsControl.Add(item);
}
}
// Optional
//AllFormsControl.Add(nControl);
}
然后,您可以運行:
InitControlList(this);
祝好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.