2012-08-13 52 views
1

我想檢索屬於Form或UserControl組件集合一部分的所有組件。 組件集合由VS winforms設計器添加。組件變量是私有的,問題是如何從所有後代中檢索所有組件。我想有一個方法返回類型層次結構中的組件列表。例如,假設我有MyForm(BaseForm的後代)和BaseForm(Form的後代)。我想把方法「GetComponents」返回MyForm和BaseForm的組件。檢索所有子類中的所有winforms組件

您是否建議使用反射之外的其他選項?

+0

結帳[this answer](http://stackoverflow.com/a/371829/1495442) – Ria 2012-08-13 09:40:08

+0

這在運行時不起作用。我想實現的是在我的基類中有一個返回所有子類中所有組件列表的方法。 – Zvonko 2012-08-13 11:45:34

+0

您是否嘗試迭代Control.Controls集合?您可以編寫一個簡單的遞歸函數,將父控件(例如您的表單)作爲輸入,然後在其控件集合中循環。我使用這種技術來以編程方式在窗體中的每個組件上附加/分離事件處理程序。 – Edenbauer 2012-08-13 16:05:05

回答

1

前一段時間我已經實現,其中我創建的自定義鹼的形式和控制實現的溶液,加入一個屬性並覆蓋在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:以同樣的方式我也創建了統計上的主線程調用數性能計數器。