我知道如何将表单切换为表单,但问题是从Form B
切换到Form A
时。它始终创建Form A
的新实例。
我该如何避免这种行为?
答案 0 :(得分:-2)
您要找的是Singleton。
对于一个非常基本的方法,你可以采取这个:
public partial class Form1 : Form
{
public static Form1 Instance { get; set; } //Create an Instance Object of your Window
public Form1()
{
InitializeComponent();
}
//Your call to open the Window
private void OpenForm2()
{
if (Form2.Instance == null)//Check if Form2 has already been created
{
//if not: go create a new one !
Form2.Instance = new Form2();
}
//Instance of Form2 is already created => open that one
Form2.Instance.Show();
}
}
public partial class Form2 : Form
{
public static Form2 Instance { get; set; }
public Form2()
{
InitializeComponent();
}
}