如何让父母控制所有的孩子?我正在寻找一个代码示例,如何获取父控件的所有子项。我不知道该怎么办。foreach(控件中的控件控件){if(control.HasChildren){??如果你只想要直接的孩子使用...varchildren=control.Controls.OfType();...如果您想要层次结构中的所有控件(即树中某个控件下方的所有控件),请使用:privateIEnumerableGetControlHierarchy(Controlroot){varqueue=newQueue();queue.Enqueue(根);做{varcontrol=queue.Dequeue();收益回报控制;foreach(varchildincontrol.Controls.OfType())queue.Enqueue(child);}while(queue.Count>0);然后,您可以在表单内容中使用以下内容:privatevoidbutton1_Click(objectsender,EventArgse){///在列表中获取表单层次结构中的所有控件foreach(varcontrolincontrolList){////dosomethingwiththiscontrol}}请注意,.ToList()将立即评估整个Enumerable,这会消除您从协程实现中获得的任何性能优势。该控件有一个MyControl.Controls集合,您可以执行一个foreach。每个Control还有一个Parent属性,它为您提供父控件。如果您需要降低未知数量的级别,您可以编写递归方法。也许对某人有用:publicvoidGetControlsCollection(Controlroot,refListAllControls,Funcfilter){foreach(Controlchildinroot.Controls){如果(childFiltered!=null)AllControls。添加(孩子);如果(child.HasControls())GetControlsCollection(child,refAllControls,filter);这是一个递归函数,用于获取可以应用过滤器的控件集合(按类型举例)。这个例子:ListresultControlList=newList();GetControlsCollection(rootControl,refresultControlList,newFunc(ctr=>(ctrisDropDownList)?ctr:null));它将返回rootControl中的所有DropDownLists及其所有子节点可能过于复杂,但是使用Linq和上面/其他地方的一些想法:以上是C#学习教程:如何制作父控件的所有子节点?如果分享的内容对你有用,需要了解更多C#学习教程,希望你多多关注——publicstaticIEnumerableGetAllChildren(thisControlroot){varq=newQueue(root.Controls.投掷());while(q.Any()){varnext=q.Dequeue();next.Controls.Cast().ToList().ForEach(q.Enqueue);接下来收益回报;}}代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
