自定义方法“;GetControlsOfType“;似乎在上升控制结构也在下降
本文关键字:控制结构 GetControlsOfType 自定义方法 | 更新日期: 2023-09-27 18:25:10
我有一个自定义方法GetControlsOfType,看起来像这样:
public static List<TControl> GetControlsOfType<TControl>(this Control control) where TControl : Control
{
return (from n in control.Controls.Cast<Control>().Descendants(c => c.Controls.Cast<Control>())
where n is TControl
select (TControl)n).ToList();
}
它取决于这个扩展:
static public IEnumerable<T> Descendants<T>(this IEnumerable<T> source,
Func<T, IEnumerable<T>> DescendBy)
{
foreach (T value in source)
{
yield return value;
foreach (T child in DescendBy(value).Descendants<T>(DescendBy))
{
yield return child;
}
}
}
如果我有这样的控制结构(RadEditor只是一个制作富文本的Telerik控件):
MyWebPage.aspx
- MyUserControl1.ascx
- MyRadEditor1
- MyUserControl2.ascx
- MyRadEditor2
如果MyUserControl2.ascx调用下面的方法,我会看到MyRadEditor1和2。
public static void SetRadEditors(this UserControl control, object entity)
{
control.GetControlsOfType<RadEditor>().ForEach(editor =>
{
// Should only show MyRadEditor2, but shows MyRadEditor1 and MyRadEditor2
});
}
有人能帮我理解为什么会发生这种情况吗?
现在不确定(太累了,无法调试..:-)。
无论如何,试试这个:
public static IEnumerable<T> FindControlsRecursive<T>(this Control root)
{
foreach (Control child in root.Controls)
{
if (child is T)
{
yield return child;
}
if (child.Controls.Count > 0)
{
foreach (Control c in child.FindControlsRecursive<T>())
{
yield return c;
}
}
}
}