使用控制器和事件来解耦表单
做这种事情的正确方法是通过引入一个Controller
类来将两种形式相互解耦,并使用events
来表示状态变化。
这是一个例子。
首先,创建一个新的默认 Windows 窗体应用程序WindowsFormsApplication1
,并添加两个窗体form1
和form2
.
然后添加form1
一个名为“button1”的按钮和一个名为“label1”的标签。
然后添加到form2
一个名为“checkbox1”的复选框。
在form1
设计器中,双击按钮为其添加点击处理程序。
在form2
设计器中,双击复选框为其添加更改处理程序。
现在添加一个名为“Controller”的新类,并向其中添加以下代码:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
internal sealed class Controller
{
public void RunForm1()
{
_form1 = new Form1();
// The next line defines our response to the button being pressed in Form1
_form1.ButtonClicked += (sender, args) => showForm2();
Application.Run(_form1);
}
private void showForm2()
{
var form2 = new Form2();
// The next line defines our response to the checkbox changing in Form2.
form2.CheckBoxChanged +=
(sender, args) =>
_form1.SetLabel("Checkbox = " + ((CheckBox)sender).Checked);
form2.ShowDialog(_form1);
}
private Form1 _form1 ;
}
}
现在改成Form1.cs
这样:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1: Form
{
// Here's where we announce our event handler to the world:
public event EventHandler ButtonClicked;
public Form1()
{
InitializeComponent();
}
public void SetLabel(string text)
{
label1.Text = text;
}
private void button1_Click(object sender, EventArgs e)
{
// We make a copy of ButtonClicked before checking it for null because
// in a multithreaded environment some other thread could change it to null
// just after we checked it for nullness but before we call it, which would
// cause a null reference exception.
// A copy cannot be changed by another thread, so that's safe to use:
var handler = ButtonClicked;
if (handler != null)
handler(sender, e);
}
}
}
并更改Form2.cs
为:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2: Form
{
// Here's the event handler for the check box:
public event EventHandler CheckBoxChanged;
public Form2()
{
InitializeComponent();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
var handler = CheckBoxChanged;
if (handler != null)
handler(sender, e);
}
}
}
最后,改成Program.cs
这样:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Controller controller = new Controller();
controller.RunForm1();
}
}
}
现在运行程序并单击按钮,然后单击复选框几次。您将看到 Form1 中的标签发生变化。
通过这种方式,您已经将控制逻辑完全解耦Form1
并Form2
放入单独的 Controller 类中。