Recursively notify child controls via C#

前端 未结 4 1994
执笔经年
执笔经年 2020-12-18 08:56

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 o

相关标签:
4条回答
  • 2020-12-18 09:27
    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);
    
    0 讨论(0)
  • 2020-12-18 09:37

    You are going to need a recursive method to do this (as below), because controls can have children.

    void NotifyChildren( control parent )
    {
        if ( parent == null ) return;
        parent.notify();
        foreach( control child in parent.children )
        {
            NotifyChildren( child );
        }
    }
    
    0 讨论(0)
  • 2020-12-18 09:38

    The answer from MusiGenesis is elegant, (typical in a good way), nice and clean.

    But just to offer an alternative using lambda expressions and an 'Action' for a different type of recursion:

    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);
    
    0 讨论(0)
  • 2020-12-18 09:44

    No, there isn't. You must roll out your own.

    On a side note - WPF has "routed events" which is exactly this and more.

    0 讨论(0)
提交回复
热议问题