我有一个页面,我必须根据用户选择动态加载控件。 让我们说我有这样的事情:
public static readonly Dictionary<string, string> DynamicControls = new Dictionary<string, string>
{
{ "UserCtrl1", "~/Controls/UserCtrl1.ascx" },
{ "UserCtrl2", "~/Controls/UserCtrl2.ascx" },
{ "UserCtrl3", "~/Controls/UserCtrl3.ascx" },
{ "UserCtrl4", "~/Controls/UserCtrl4.ascx"}
};
现在让我们说,而不是在加载控件的页面上,代码是这样的:
protected void Page_Load(object sender, EventArgs e)
{
SomePanel.Controls.Add(GetControl());
}
private Control GetControl()
{
string dynamicCtrl = CurrentItem.DynamicControl;
string path = SomeClass.DynamicControls[dynamicCtrl];
Control ctrl = null;
//TODO: find a better way to load the controls
switch (dynamicCtrl)
{
case "UserCtrl1":
{
ctrl = (UserCtrl1)LoadControl(path);
}
break;
case "UserCtrl2":
{
ctrl = (UserCtrl2)LoadControl(path);
}
break;
case "UserCtrl3":
{
ctrl = (UserCtrl3)LoadControl(path);
}
break;
default:
{
throw new ApplicationException("Invalid dynamic control added.");
}
}
return ctrl;
}
该页面包含所需的注册声明。知道我怎么能摆脱这个丑陋的开关声明吗?
答案 0 :(得分:9)
您无需从LoadControl转换结果。
这应该做:
private Control GetControl()
{
string dynamicCtrl = CurrentItem.DynamicControl;
string path = SomeClass.DynamicControls[dynamicCtrl];
Control ctrl = LoadControl(path);
return ctrl;
}
答案 1 :(得分:1)
你可能想要这样的东西(伪代码):
foreach key in dictionary if key = dynamicControl then ctrl = (Type.GetType(key))LoadControl(dictionary.get(key)) end if next
答案 2 :(得分:0)
你能不能在字典上使用foreach并在那里进行测试和LoadControl?
答案 3 :(得分:0)
这不会有帮助,因为需要切换到正确的控制类型。