[英]How to find a control from controls of controls collection recursively?
My control " MyTextBox1 " add dynamically on form1 under container1 control. 我的控件“ MyTextBox1 ”在container1控件下动态添加到form1上。 This form1 can be child of form2 and form2 can be child of form3 and so on how can I find my control from multi controls collection?
这个form1可以是form2的子级,而form2可以是form3的子级,依此类推,如何从多控件集合中找到我的控件?
eg MyTextBox1 exists in 例如MyTextBox1存在于
form3.form2.form1.Container1.MyTextBox1
form3.form2.form1.Container1.MyTextBox1
how to find my control by name from multi control collections? 如何从多个控件集合中按名称查找控件?
I do not want to use recursive foreach control collection. 我不想使用递归的foreach控件集合。 I am looking for an smart/short code like controls.Find().
我正在寻找类似controls.Find()的智能/简短代码。
If you don't want to put it recoursive , you can try BFS (Breadth First Search); 如果您不想把它放长篇大论 ,可以尝试BFS (宽度优先搜索); let's implement it as an extension method :
让我们将其实现为扩展方法 :
public static class ControlExtensions {
public static IEnumerable<Control> RecoursiveControls(this Control parent) {
if (null == parent)
throw new ArgumentNullException(nameof(parent));
Queue<Control> agenda = new Queue<Control>(parent.Controls.OfType<Control>());
while (agenda.Any()) {
yield return agenda.Peek();
foreach (var item in agenda.Dequeue().Controls.OfType<Control>())
agenda.Enqueue(item);
}
}
}
Then you can use it as 然后您可以将其用作
// Let's find Button "MyButton1" somewhere on MyForm
// (not necessary directly, but may be on some container)
Button myBytton = MyForm
.RecoursiveControls()
.OfType<Button>()
.FirstOrDefault(btn => btn.Name == "MyButton1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.