查找有关使用LINQ一个WinForms控制?LINQ、WinForms

2023-09-02 01:48:03 作者:开到荼靡

我想找到一个优雅的方式来获得控制上的 Windows窗体的名字形式。例如:

I am trying to find an elegant way to get controls on a Windows Forms form by name. For example:

MyForm.GetControl "MyTextBox"

...

但是,这确保它通过所有控件递归。

But this has to make sure it goes through all the controls recursively.

什么是实现这个使用LINQ 这里输入链接的描述最优雅的方式?

What's the most elegant way to implement this using LINQenter link description here?

推荐答案

LINQ不一定是最适合未知深入递归;只要使用正规的code ...

LINQ isn't necessarily best-suited to unknown-depth recursion; just use regular code...

public static Control FindControl(this Control root, string name) {
    if(root == null) throw new ArgumentNullException("root");
    foreach(Control child in root.Controls) {
        if(child.Name == name) return child;
        Control found = FindControl(child, name);
        if(found != null) return found;
    }
    return null;
}

Control c = myForm.GetControl("MyTextBox");

或者,如果你不喜欢上面的递归:

Or if you don't like the recursion above:

public Control FindControl(Control root, string name) {
    if (root == null) throw new ArgumentNullException("root");
    var stack = new Stack<Control>();
    stack.Push(root);
    while (stack.Count > 0) {
        Control item = stack.Pop();
        if (item.Name == name) return item;
        foreach (Control child in item.Controls) {
            stack.Push(child);
        }
    }
    return null;
}
 
精彩推荐
图片推荐