繁体   English   中英

将用户控件从类型名称转换为自定义控件类型?

[英]Cast user-control to custom control type from type name?

我正在将动态指定的用户控件加载到父(用户)控件中的占位符中,如下所示:

// dynamically load instance of chosen chart control
string chartClassName = ConfigurationManager.AppSettings["ChartControlClass"];
_chartControl = (IOutputChart)LoadControl(chartClassName + ".ascx");
// add to place-holder
if (chartClassName == "OutputChart_Dundas") phChart.Controls.Add((OutputChart_Dundas)_chartControl);
else if (chartClassName == "OutputChart_Microsoft") phChart.Controls.Add((OutputChart_Microsoft)_chartControl);
else if (chartClassName == "OutputChart_Telerik") phChart.Controls.Add((OutputChart_Telerik)_chartControl);

显然, _chartControl每次都显式地_chartControl变量会更好-是否有更干净的方法? 每个用户控件都实现IOutputChart接口; 但是,我不能直接使用它,因为Controls.Add()需要一个Control对象。

您不仅可以将所有这些转换为Control吗?

phChart.Controls.Add((Control)_chartControl);

我假设您所有的控件都派生自Control基类。 然后,为什么不将_chartControlControl并添加它呢?

_chartControl = (Control)LoadControl(chartClassName + ".ascx");
phChart.Controls.Add(_chartControl);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM