public static IEnumerable<Control> FlattenChildren(this Control control)
{
var children = control.Controls.Cast<Control>();
return children.SelectMany(c => FlattenChildren(c)).Concat(children);
}
public static IList<T> GetAllControlsRecusrvive<T>(Control control) where T :Control
{
var rtn = new List<T>();
foreach (Control item in control.Controls)
{
var ctr = item as T;
if (ctr!=null)
{
rtn.Add(ctr);
}
else
{
rtn.AddRange(GetAllControlsRecusrvive<T>(item));
}
}
return rtn;
}
//Returns all controls of a certain type in all levels:
public static IEnumerable<TheControlType> AllControls<TheControlType>( this Control theStartControl ) where TheControlType : Control
{
var controlsInThisLevel = theStartControl.Controls.Cast<Control>();
return controlsInThisLevel.SelectMany( AllControls<TheControlType> ).Concat( controlsInThisLevel.OfType<TheControlType>() );
}
//(Another way) Returns all controls of a certain type in all levels, integrity derivation:
public static IEnumerable<TheControlType> AllControlsOfType<TheControlType>( this Control theStartControl ) where TheControlType : Control
{
return theStartControl.AllControls().OfType<TheControlType>();
}
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace MyApp.Extensions
{
public static class ControlExtensions
{
public static IEnumerable<Control> FlattenChildren<T>(this Control control)
{
return control.FlattenChildren().OfType<T>().Cast<Control>();
}
public static IEnumerable<Control> FlattenChildren(this Control control)
{
var children = control.Controls.Cast<Control>();
return children.SelectMany(c => FlattenChildren(c)).Concat(children);
}
}
}
示例用法
已添加到窗体的_Load事件...
//Show the name of each ComboBox on a form (even nested controls)
foreach (ComboBox cb in this.FlattenChildren<ComboBox>())
{
Debug.WriteLine(cb.Name);
}
//Get the number of controls on a form
Debug.WriteLine("Control count on form: " + this.FlattenChildren().Count());
4条答案
按热度按时间tcbh2hod1#
我使用一个扩展方法来扁平化控件层次结构,然后应用过滤器,所以这是使用自己递归方法。
方法如下所示
tquggr8v2#
我使用这个通用递归方法:
这个方法的假设是,如果控件是T,则该方法不会查看其子控件。如果您也需要查看其子控件,则可以轻松地相应更改它。
1qczuiv03#
要改进上述答案,将返回类型更改为
zlhcx6iw4#
12年后,我喜欢这个答案(https://stackoverflow.com/a/2209896/1039753),并希望按照KeithS的建议,构建一个选项来传递类型约束,以便只返回所需的控件类型。
扩展方法
示例用法
已添加到窗体的
_Load
事件...