【发布时间】:2011-12-10 02:55:33
【问题描述】:
我需要遍历正在开发的 UserControl 中的所有控件和组件。
我试过了:
public void Traverse(Control cnt)
{
foreach (Control c in cnt.Controls)
{
if (c.HasChildren) Traverse(c);
Debug.Print(c.Name); // For debugging purpose only
// My code goes here
}
}
当函数遇到 ToolStrip 时出现问题:它没有子项,但有项 (ToolStripItemCollection: IList, ICollection, IEnumerable)。
我不关心类型:使用反射我需要设置一些属性,所以我觉得有对象作为结果。
如何获取 UserControl 中每个组件的名称?
谢谢
【问题讨论】:
-
也许你应该检查
if(c is IEnumerable)并枚举包含的对象 -
@LB: 无济于事:当您遍历 UserControl 并找到 ToolStrip 时,如果不硬写
in ts.Items... 并且我不想为我控制的每个可能的子项编写代码(好吧,如果可能的话) -
@Marco - 我删除了我的答案。为了以“通用”方式通过控件并查看是否有 IEnumerables 等,它最终涉及反射。
-
@CAbbott:感谢您的帮助 :)
-
ToolStripItem 类不是从 Control 派生的。显然,您无法使用您现在拥有的方法签名遍历它们。如果(c 是 ToolStrip),则做一些不同的事情。