是的,在它们自己的类中创建名为 UserControls 的新对象。您可以通过编程方式添加和删除它们,但可以在设计器中创建它们。
为避免在更改控件时出现闪烁,请执行以下操作:
Control ctlOld = frmMain.Controls[0]; // this will allow you to remove whatever control is in there, allowing you to keep your code generic.
ctlNextControl ctl = new ctlNextControl(); // this is the control you've created in another class
frmMain.Controls.Add(ctlNextControl);
frmMain.Controls.Remove(ctlOld);
创建您的用户控件,并为它们命名,我现在将命名一些示例:
ctlGear
ctlMap
ctlGraph
ctlCar
ctlPerson
将这 5 个文件作为用户控件添加到您的项目中。随心所欲地设计它们。
为不同的按钮创建一个枚举以便于使用:
public enum ControlType {
Gear,
Map,
Graph,
Car,
Person
}
创建它们后,在每个按钮的按钮单击事件中,添加对这个新方法的调用:
private void SwitchControls(ControlType pType) {
// Keep a reference to whichever control is currently in MainPanel.
Control ctlOld = MainPanel.Controls[0];
// Create a new Control object
Control ctlNew = null;
// Make a switch statement to find the correct type of Control to create.
switch (pType) {
case (ControlType.Gear):
ctlNew = new ctlGear();
break;
case (ControlType.Map):
ctlNew = new ctlMap();
break;
case (ControlType.Graph):
ctlNew = new ctlGraph();
break;
case (ControlType.Car):
ctlNew = new ctlCar();
break;
case (ControlType.Person):
ctlNew = new ctlPerson();
break;
// don't worry about a default, unless you have one you would want to be the default.
}
// Don't try to add a null Control.
if (ctlNew == null) return();
MainPanel.Controls.Add(ctlNew);
MainPanel.Controls.Remove(ctlOld);
}
然后在你的按钮点击事件中,你可以有这样的东西:
private void btnGear.Click(object sender, EventArgs e) {
SwitchControls(ControlType.Gear);
}
其他的点击事件也是一样,只是把参数中的ControlType改了。