如何让父母控制的所有孩子?
我正在寻找一个代码示例,如何获得父控件的所有子代。
我不知道怎么做。
foreach (Control control in Controls) { if (control.HasChildren) { ?? } }
如果您只想要直系孩子,请使用
... var children = control.Controls.OfType(); ...
如果您想要层次结构中的所有控件(即树中某些控件下的所有控件),请使用:
private IEnumerable GetControlHierarchy(Control root) { var queue = new Queue (); queue.Enqueue(root); do { var control = queue.Dequeue(); yield return control; foreach (var child in control.Controls.OfType ()) queue.Enqueue(child); } while (queue.Count > 0); }
然后,您可以在表单中使用以下内容:
private void button1_Click(object sender, EventArgs e) { /// get all of the controls in the form's hierarchy in a List<> var controlList = GetControlHierarchy(this).ToList(); foreach (var control in controlList) { /// do something with this control } }
请注意.ToList()
将立即评估整个Enumerable,这消除了您从协程实现中获得的任何性能优势。
控件有一个MyControl.Controls
集合,你可以做一个foreach
。
每个Control还有一个Parent
属性,它为您提供父控件。
如果需要降低未知数量的级别,可以编写递归方法。
也许它可能对某人有用:
public void GetControlsCollection(Control root,ref List AllControls, Func filter) { foreach (Control child in root.Controls) { var childFiltered = filter(child); if (childFiltered != null) AllControls.Add(child); if (child.HasControls()) GetControlsCollection(child, ref AllControls, filter); } }
这是递归函数,用于获取可能应用filter的控件集合(按类型进行示例)。 而这个例子:
List resultControlList = new List (); GetControlsCollection(rootControl, ref resultControlList, new Func(ctr => (ctr is DropDownList)? ctr:null ));
它将返回rootControl中的所有DropDownLists及其所有子节点
可能过于复杂,但使用Linq和来自上面/其他地方的一些想法:
上述就是C#学习教程:如何让父母控制的所有孩子?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public static IEnumerable GetAllChildren(this Control root) { var q = new Queue (root.Controls.Cast ()); while (q.Any()) { var next = q.Dequeue(); next.Controls.Cast ().ToList().ForEach(q.Enqueue); yield return next; } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1250999.html