我是 C#.Net 新手。 我有一个表格,里面有一些面板。其中一个面板是 MainPanel。启动后,MainPanel 为空。根据用户的选择,我想在其中加载一些控件。类似于Java中的CardLayout!每个面板都有很多控件,我不想以编程方式添加它们。事实上,问题是“有没有一种方法可以在设计器中设计一些面板,并根据用户选择显示/隐藏它们,全部以一种形式?”
谢谢。
最佳答案
是的,在自己的类中创建名为 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 个文件作为 UserControl 添加到您的项目中。按照您想要的方式设计它们。
为不同的按钮创建一个枚举以方便使用:
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 即可。
关于c# - 如何在 C# 中的表单中使用具有不同控件的多个面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11039371/