【发布时间】:2018-07-02 20:19:28
【问题描述】:
我在表单上显示 UserControl 时遇到问题。
简而言之程序:
- 在 Form1 中有一个按钮。单击此按钮后,在面板(容器)中,我的第一个 UserControl(new.cs)被动态加载。
- 在那个面板上,我有另一个按钮,它指向另一个 UserControl (choice.cs),我想在 Form1 上的同一个面板(容器)中显示它。
第一点效果很好,但我对第二点有疑问。我想我必须更正choice_button_Click 功能。有什么简单的方法吗?
这是我的代码:
Form1.cs:
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void new_button_Click(object sender, EventArgs e)
{
if (!container.Controls.Contains(@new.Instance))
{
container.Controls.Add(@new.Instance);
@new.Instance.Dock = DockStyle.Fill;
@new.Instance.BringToFront();
}
else
{
@new.Instance.BringToFront();
}
}
public Panel getContainer()
{
return container;
}
}
}
new.cs:
namespace WindowsFormsApp1
{
public partial class @new : UserControl
{
private static @new _instance;
public static @new Instance
{
get
{
if (_instance == null)
_instance = new @new();
return _instance;
}
}
public @new()
{
InitializeComponent();
}
private void choice_button_Click(object sender, EventArgs e)
{
using (Form1 main = new Form1())
{
if (!main.getContainer().Controls.Contains(choice.Instance))
{
main.getContainer().Controls.Add(choice.Instance);
choice.Instance.Dock = DockStyle.Fill;
choice.Instance.BringToFront();
}
else
{
choice.Instance.BringToFront();
}
}
}
}
}
choice.cs:
namespace WindowsFormsApp1
{
public partial class choice : UserControl
{
private static choice _instance;
public static choice Instance
{
get
{
if (_instance == null)
_instance = new choice();
return _instance;
}
}
public choice()
{
InitializeComponent();
}
}
}
【问题讨论】: