通过C#递归通知子控件 [英] Recursively notify child controls via C#

查看:91
本文介绍了通过C#递归通知子控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个窗体 MainForm ,它是Windows窗体窗体,其中包含许多子控件。我想在 MainForm 上调用一个函数来通知其所有子级。 Windows窗体表单是否提供执行此操作的方法?我玩过更新,刷新和无效播放,没有成功。

I have a form MainForm which is a Windows Forms form that contains many child controls. I want to call one function on MainForm that notifies all of its children. Does the Windows Forms form provide a means to do this? I played with update, refresh and invalidate with no success.

推荐答案

foreach (Control ctrl in this.Controls)
{
    // call whatever you want on ctrl
}

如果要访问表单上的所有控件,以及表单上每个控件上的所有控件(以此类推,以递归方式),请使用如下函数:

If you want access to all controls on the form, and also all the controls on each control on the form (and so on, recursively), use a function like this:

public void DoSomething(Control.ControlCollection controls)
{
    foreach (Control ctrl in controls)
    {
        // do something to ctrl
        MessageBox.Show(ctrl.Name);
        // recurse through all child controls
        DoSomething(ctrl.Controls);
    }
}

...您最初通过传入表单的控件集合,如下所示:

... which you call by initially passing in the form's Controls collection, like this:

DoSomething(this.Controls);

这篇关于通过C#递归通知子控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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