循环浏览窗体的所有控件,即使是GroupBoxes中的控件 [英] Loop through all controls of a Form, even those in GroupBoxes

查看:104
本文介绍了循环浏览窗体的所有控件,即使是GroupBoxes中的控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在表单上的所有文本框中添加一个事件:

I'd like to add an event to all TextBoxes on my Form:

foreach (Control C in this.Controls)
{
    if (C.GetType() == typeof(System.Windows.Forms.TextBox))
    {
        C.TextChanged += new EventHandler(C_TextChanged);
    }
}

问题是它们存储在几个GroupBox中,我的循环看不到它们。我可以分别遍历每个 GroupBox 的控件,但是有可能在一个循环中以一种简单的方式完成所有这些操作吗?

The problem is that they are stored in several GroupBoxes and my loop doesn't see them. I could loop through controls of each GroupBox individually but is it possible to do it all in a simple way in one loop?

推荐答案

表单和容器控件的 Controls 集合仅包含直接子级。为了获得所有控件,您需要遍历控件树并递归应用此操作

The Controls collection of Forms and container controls contains only the immediate children. In order to get all the controls, you need to traverse the controls tree and to apply this operation recursively

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 集合。因此,您可以在表单中调用这样的方法:

Note: The form derives (indirectly) from Control as well and all controls have a Controls collection. So you can call the method like this in your form:

AddTextChangedHandler(this);






更通用的解决方案是创建扩展名将操作递归地应用于所有控件的方法。在静态类(例如 WinFormsExtensions )中,添加以下方法:


A more general solution would be to create an extension method that applies an action recursively to all controls. In a static class (e.g. WinFormsExtensions) add this method:

public static void ForAllControls(this Control parent, Action<Control> action)
{
    foreach (Control c in parent.Controls) {
        action(c);
        ForAllControls(c, action);
    }
}

静态类名称空间必须是可见的,即,如果在另一个命名空间中,则使用声明添加一个适当的

The static classes namespace must be "visible", i.e., add an appropriate using declaration if it is in another namespace.

然后您可以这样称呼它,其中是表格;您还可以将 this 替换为必须影响其嵌套控件的表单或控件变量:

Then you can call it like this, where this is the form; you can also replace this by a form or control variable whose nested controls have to be affected:

this.ForAllControls(c =>
{
    if (c.GetType() == typeof(TextBox)) {
        c.TextChanged += C_TextChanged;
    }
});

这篇关于循环浏览窗体的所有控件,即使是GroupBoxes中的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆