【问题标题】:Navigate through Controls and Components浏览控件和组件
【发布时间】: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),则做一些不同的事情。

标签: c# winforms


【解决方案1】:

我编写了一个版本,它遍历控件的属性并查找带有ICollections 的IComponents:

方法:

private void GetControls(ICollection controls, IList<string> names)
{
    foreach (var ctl in controls)
    {
        if (ctl is IComponent)
        {
            var name = ctl.GetType().GetProperty("Name");
            if (name != null)
                names.Add((string) name.GetValue(ctl, null));

            foreach (var property in ctl.GetType().GetProperties())
            {
                var prop = property.GetValue(ctl, null);
                if (prop is ICollection)
                    GetControls((ICollection)prop, names);
            }
        }
    }
}

调用:

var ctlNames = new List<string>();
GetControls(Controls, ctlNames);

我已经对此进行了测试,它似乎可以找到表单上的每个控件。我还没有对它进行各种控制测试,我无法保证它的效率。

【讨论】:

  • 效率不高,但这不是你的错。无论如何,你的答案就是我正在寻找的。非常感谢!!
  • 是的,可能有一些方法可以收紧它查看的属性列表。很高兴它对你有用。
猜你喜欢
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
相关资源
最近更新 更多