且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过名字获得控制权,包括孩子

更新时间:2023-12-03 19:21:04

我实际上在工作中写了一些扩展方法来完成此任务:

I actually wrote some extension methods at work to do just this thing:

public static class MyExensions ()
{
    public static Control FindControlRecursively (this Control control, string name)
    {
        Control result = null;

        if (control.ID.Equals (name))
        {
            result = control;
        }
        else
        {
            foreach (var child in control.Children)
            {
                result = child.FindControlRecursively (name);

                if (result != null)
                {
                    break;
                }
            }
        }

        return result;
    }

    public static T FindControlRecursively<T> (this Control control, string name)
        where T: Control
    {
        return control.FindControlRecursively (name) as T;
    }
}

注意:为方便起见,删除了空检查

您可以使用它来查找表单上的 TextBox 因此:

You can use it to find, say, a TextBox on your form like so:

public class MyForm : Form
{
    public void SetSomeText ()
    {
        var control = this.FindControlRecursively<TextBox> ("myTextboxName");

        if (control != null)
        {
            control.Text = "I found it!";
        }

        // Or...

        var control2 = this.FindControlRecursively ("myTextboxName2") as TextBox;

        if (control != null)
        {
            control2.Text = "I found this one, also!";
        }
    }
}

修改

当然,这是一个 depth-first 算法,根据控制链的深度,该算法可能会变慢。如果发现速度太慢,则可以重写它以使用 breadth-first 算法。

Of course, this is a depth-first algorithm, which might be slow depending on how deep your control chain is. You might rewrite it to use a breadth-first algorithm if you see that it is too slow.