繁体   English   中英

通过C#递归通知子控件

[英]Recursively notify child controls via C#

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

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

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

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);
    }
}

...通过最初传入表单的Controls集合调用,如下所示:

DoSomething(this.Controls);

MusiGenesis的答案很优雅,(典型的很好),干净整洁。

但只是为了使用lambda表达式提供替代方法,并为不同类型的递归提供“Action”:

Action<Control> traverse = null;

//in a function:
traverse = (ctrl) =>
    {
         ctrl.Enabled = false; //or whatever action you're performing
         traverse = (ctrl2) => ctrl.Controls.GetEnumerator();
    };

//kick off the recursion:
traverse(rootControl);

不,没有。 你必须推出自己的。

在旁注 - WPF有“路由事件”,这正是这个和更多。

您将需要一个递归方法来执行此操作(如下所示),因为控件可以有子项。

void NotifyChildren( control parent )
{
    if ( parent == null ) return;
    parent.notify();
    foreach( control child in parent.children )
    {
        NotifyChildren( child );
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM