动态添加控件而不单调
Adding controls dynamically without it being monotonous
首先我想不出比这个更好的标题了
目前我有一个从 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;
}
是否可以将重复的代码变成一个方法,或者有更好的方法吗?
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
首先我想不出比这个更好的标题了
目前我有一个从 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;
}
是否可以将重复的代码变成一个方法,或者有更好的方法吗?
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