前一段時間我已經實現,其中我創建的自定義鹼的形式和控制實現的溶液,加入一個屬性並覆蓋在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:以同樣的方式我也創建了統計上的主線程調用數性能計數器。
結帳[this answer](http://stackoverflow.com/a/371829/1495442) – Ria 2012-08-13 09:40:08
這在運行時不起作用。我想實現的是在我的基類中有一個返回所有子類中所有組件列表的方法。 – Zvonko 2012-08-13 11:45:34
您是否嘗試迭代Control.Controls集合?您可以編寫一個簡單的遞歸函數,將父控件(例如您的表單)作爲輸入,然後在其控件集合中循環。我使用這種技術來以編程方式在窗體中的每個組件上附加/分離事件處理程序。 – Edenbauer 2012-08-13 16:05:05