我有一个名为 A
的 Form
。
A
包含许多不同的控件,包括一个主要的 GroupBox
。此 GroupBox
包含许多表格和其他 GroupBox
。我想找到一个控件,例如A
中的选项卡索引 9,但我不知道哪个 GroupBox
包含此控件。
我该怎么做?
最佳答案
递归...
public static IEnumerable<T> Descendants<T>( this Control control ) where T : class
{
foreach (Control child in control.Controls) {
T childOfT = child as T;
if (childOfT != null) {
yield return (T)childOfT;
}
if (child.HasChildren) {
foreach (T descendant in Descendants<T>(child)) {
yield return descendant;
}
}
}
}
您可以像这样使用上面的函数:
var checkBox = (from c in myForm.Descendants<CheckBox>()
where c.TabIndex == 9
select c).FirstOrDefault();
这将在 TabIndex 为 9 的表单中的任何位置获得第一个 CheckBox。显然,您可以使用任何您想要的标准。
如果您不是 LINQ 的粉丝查询语法,上面可以重写为:
var checkBox = myForm.Descendants<CheckBox>()
.FirstOrDefault(x=>x.TabIndex==9);
关于c# - 如何在 Windows 窗体中获取窗体的所有控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2735190/