首先,我无法想到比这更好的标题
目前我有一个方法可以从switch语句动态创建控件。
除控件本身外,每个控件的代码都相同。
代码:
switch (control)
{
case "TextBox":
TextBox txt = new TextBox();
txt.Name = "txt" + labeltext;
txt.Margin = _controlMargin;
txt.HorizontalAlignment = HorizontalAlignment.Stretch;
txt.FlowDirection = FlowDirection.LeftToRight;
txt.HorizontalContentAlignment = HorizontalAlignment.Left;
break;
case "ComboBox":
ComboBox cbo = new ComboBox();
cbo.Name = "cbo" + labeltext;
cbo.Margin = _controlMargin;
cbo.HorizontalAlignment = HorizontalAlignment.Stretch;
cbo.FlowDirection = FlowDirection.LeftToRight;
cbo.HorizontalContentAlignment = HorizontalAlignment.Left;
break;
}
是否可以将重复代码转换为方法,或者有更好的方法吗?
答案 0 :(得分:0)
Control control = null;
switch (controlType)
{
case "TextBox":
control = new TextBox();
control.Name = "txt + labelText;
break;
case "ComboBox":
control = new ComboBox();
control.Name = "cbo" + labelText;
break;
}
control.Margin = _controlMargin;
control.HorizontalAlignment = HorizontalAlighment.Stretch;
control.FlowDirection = FlowDirection.LeftToRight;
control.HorizontalContentAlignment = HorizontalAlignment.Left