The Controls
表单和容器控件的集合仅包含直接子级。为了获取所有控件,您需要遍历控件树并递归地应用此操作
private void AddTextChangedHandler(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c.GetType() == typeof(TextBox)) {
c.TextChanged += new EventHandler(C_TextChanged);
} else {
AddTextChangedHandler(c);
}
}
}
注:该表格(间接)源自Control
以及所有控件都有一个Controls
收藏。所以你可以在你的表单中调用这样的方法:
AddTextChangedHandler(this);
更通用的解决方案是创建一个扩展方法,将操作递归地应用于所有控件。在静态类中(例如WinFormsExtensions
)添加这个方法:
public static void ForAllControls(this Control parent, Action<Control> action)
{
foreach (Control c in parent.Controls) {
action(c);
ForAllControls(c, action);
}
}
静态类命名空间必须是“可见的”,即添加适当的using
声明(如果它位于另一个命名空间中)。
然后你可以这样称呼它,其中this
是形式;你也可以更换this
通过其嵌套控件必须受到影响的表单或控件变量:
this.ForAllControls(c =>
{
if (c.GetType() == typeof(TextBox)) {
c.TextChanged += C_TextChanged;
}
});