使用LINQ,您如何获得所有标签控件

Joh*_*ohn 1 linq label

我想获得属于用户控件的所有标签控件的集合.我有以下代码:

        var labelControls = from Control ctl in this.Controls
                            where ctl.GetType() == typeof(Label)
                            select ctl;
Run Code Online (Sandbox Code Playgroud)

但结果是零结果.

请协助.谢谢.

编辑我也试过以下代码但没有成功.

        this.Controls
            .OfType<Label>()
            .Where(ctl => ctl.ID.Contains("myPrefix"))
            .ToList()
            .ForEach(lbl => lbl.ForeColor = System.Drawing.Color.Black);
Run Code Online (Sandbox Code Playgroud)

再次,没有成功.

Jef*_*tes 5

您确定其子控件正在解析的Label控件实际上直接包含控件吗?我怀疑它是托管标签的主控件的子代,在这种情况下,您需要递归搜索UI树以查找标签.

就像是:

public static IEnumerable<Label> DescendantLabels(this Control control)
{
   return control.Controls.DescendantLabels();
}

public static IEnumerable<Label> DescendantLabels(this ControlCollection controls)
{
    var childControls = controls.OfType<Label>();

    foreach (Control control in controls)
    {
       childControls = childControls.Concat(control.DescendantLabels());
    }

    return childControls;
}
Run Code Online (Sandbox Code Playgroud)