检索所有子类中的所有winforms组件

时间:2012-08-13 09:25:41

标签: c# .net winforms .net-4.0 user-controls

我想检索作为Form或UserControl组件集合一部分的所有组件。 组件集合由VS winforms设计者添加。组件变量是私有的,问题是如何从所有后代检索所有组件。我想有一个方法,通过类型层次结构返回组件列表。例如,假设我有MyForm(BaseForm的后代)和BaseForm(Form的后代)。我想把方法“GetComponents”返回MyForm和BaseForm的组件。

除了使用反射之外,您还建议其他选择吗?

1 个答案:

答案 0 :(得分:2)

前段时间我已经实现了我创建自定义基本表单和控件实现的解决方案,添加了一个属性并覆盖了OnLoad方法:

public partial class FormBase : Form   
{
    public FormBase ()
    {
        this.InitializeComponent();
    }

    protected ConsistencyManager ConsistencyManager { get; private set; }

    protected override void OnLoad(System.EventArgs e)
    {
        base.OnLoad(e);

        if (this.ConsistencyManager == null)
        {
            this.ConsistencyManager = new ConsistencyManager(this);
            this.ConsistencyManager.MakeConsistent();
        }
    }
}

ConsistencyManager类可查找所有控件,组件,还支持在特定控件中搜索自定义子控件。从MakeConsistent方法复制/粘贴代码:

    public void MakeConsistent()
    {
        if (this.components == null)
        {
            List<IComponent> additionalComponents = new List<IComponent>();

            // get all controls, including the current one 
            this.components =
                this.GetAllControls(this.parentControl)
                .Concat(GetAllComponents(this.parentControl))
                .Concat(new Control[] { this.parentControl });

            // now find additional components, which are not present neither in Controls collection nor in components
            foreach (var component in this.components)
            {
                IAdditionalComponentsProvider provider = GetAdditinalComponentsProvider(component.GetType().FullName);

                if (provider != null)
                {
                    additionalComponents.AddRange(provider.GetChildComponents(component));
                }
            }

            if (additionalComponents.Count > 0)
            {
                this.components = this.components.Concat(additionalComponents);
            }
        }

        this.MakeConsistent(this.components);
    }

如果有人想要完整的样品或来源,请告诉我。

祝你好运, Zvonko

PS:我也以同样的方式创建了计算主线程调用次数的性能计数器。