Finding a control on a Winforms using LINQ?

后端 未结 4 1992
灰色年华
灰色年华 2020-12-09 13:14

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

MyForm.GetControl \"MyTextBox\"

...

But t

4条回答
  •  粉色の甜心
    2020-12-09 13:34

    I don't think you can create recursive linq queries directly, but you could create a recursive method using linq:

    public IEnumerable FlattenHierarchy(this Control c)
    {
        return new[] { c }.Concat(c.Controls.Cast().SelectMany(child => child.FlattenHierarchy()));
    }
    

    This should return a sequence containing every control contained in a control hierarchy. Then finding a match is straightforward:

    public Control FindInHierarchy(this Control control, string controlName)
    {
        return control.FlattenHierarchy().FirstOrDefault(c => c.Name == controlName);
    }
    

    Personally I'd avoid using linq in this way though.

提交回复
热议问题