使用LINQ,如何获得所有标签控件 [英] Using LINQ, how do you get all label controls
本文介绍了使用LINQ,如何获得所有标签控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取属于用户控件的所有标签控件的集合.我有以下代码:
I want to get a collection of all label controls that are part of a user control. I have the following code:
var labelControls = from Control ctl in this.Controls
where ctl.GetType() == typeof(Label)
select ctl;
,但结果为零结果.
请协助.谢谢.
编辑 我还尝试了以下代码,但未成功.
Edit I have also tried the following code without success.
this.Controls
.OfType<Label>()
.Where(ctl => ctl.ID.Contains("myPrefix"))
.ToList()
.ForEach(lbl => lbl.ForeColor = System.Drawing.Color.Black);
再次,没有成功.
推荐答案
您确定要解析其子控件的控件实际上直接包含Label
控件吗?我怀疑托管标签的是主控件的子级,在这种情况下,您需要递归搜索UI树以找到标签.
Are you sure that the control whose child controls you are parsing actually directly contains Label
controls? I suspect that it is a child of the main control that is hosting the labels, in which case, you need to recursively search through the UI tree to find the labels.
类似的东西:
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;
}
这篇关于使用LINQ,如何获得所有标签控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文