gpt4 book ai didi

c# - 浏览控件和组件

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:14 25 4
gpt4 key购买 nike

我需要遍历我正在开发的 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 中每个组件的名称?
谢谢

最佳答案

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

方法:

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);

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

关于c# - 浏览控件和组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7808103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com