我有一個母版頁,其內容頁面和母版頁本身都有一些控件。所有這些控件都擴展了System.Web.UI.UserControl,有些實現了一個名爲IControlInjector的接口。在運行時查找在母版頁中呈現的控件
當主頁面加載時,是否有任何方法可以在主頁面中檢查控件樹中正在加載的控件,並找到所有實現IControlInjector接口的控件?
我有一個母版頁,其內容頁面和母版頁本身都有一些控件。所有這些控件都擴展了System.Web.UI.UserControl,有些實現了一個名爲IControlInjector的接口。在運行時查找在母版頁中呈現的控件
當主頁面加載時,是否有任何方法可以在主頁面中檢查控件樹中正在加載的控件,並找到所有實現IControlInjector接口的控件?
// put in code-behind class...
private void GatherIControlInjectors(Control control, IList<IControlInjector> controls){
foreach(Control ctrl in control){
if(ctrl is IControlInjector)
controls.Add(ctrl);
if(ctrl.Controls.Count > 0)
GatherIControlInjectors(ctrl, controls);
}
return;
}
// example
IList<IControlInjector> ctrlInjectors = new List<IControlInjector>();
GatherIControlInjectors(Master, ctrlInjectors);
相反,這樣做追溯,你可以添加一個擴展方法ControlsCollection。新增或覆蓋ControlsCollection和add方法來處理添加控件,實現特定的接口,以便你可以直接把它們粘到註冊表(例如字典或列表)。從而以強類型,快速查找方式訪問您的控件。
這是一個非常有趣的做我需要的方式 - 這樣的代碼示例的任何機會? – amateur 2010-08-09 21:15:44
你可以遞歸迭代通過主控制樹,但我不知道如何檢查一個特定的控件是否實現了某個接口。 – Jeroen 2010-08-05 17:32:28