事件的应用
1.事件模型的5个组成部分
(1)事件的拥有者(event source,对象),也称:事件的source,事件的主体,事件消息的发送者
(2)事件(event,成员)
(3)事件的响应者(event subscriber,对象),是订阅了事件的对象或类,当一个事件发生时,被通知到的类或对象就是事件的响应者
(4)事件的处理器(event handler,成员),是事件响应者的方法成员,本质上是一个回调方法
(5)事件订阅,把事件处理器与事件关联在一起,本质上是一种以委托类型为基础的约定
2.事件的几种模式:
1)事件拥有着和响应者是2个类的实例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EventTest_WindowsFramework
{
class Program
{
static void Main(string[] args)
{
Form form = new Form();
FormController formController = new FormController(form);
form.ShowDialog();
}
}
class FormController
{
private Form form;
public FormController(Form form)
{
if (form!=null)
{
this.form = form;
this.form.Click += this.FormAction;
}
}
private void FormAction(object sender, EventArgs e)
{
this.form.Text = DateTime.Now.ToString();
}
}
}
2).事件的拥有者同时也是事件的响应者
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EventTest_WindowsFramework
{
class Program
{
static void Main(string[] args)
{
MyForm myForm = new MyForm();
myForm.Click += myForm.Action;
myForm.ShowDialog();
}
}
class MyForm : Form
{
internal void Action(object sender, EventArgs e)
{
this.Text = DateTime.Now.ToString();
}
}
}
3)事件拥有者是事件响应者的一个字段成员
事件的响应者用自己的方法订阅着自己的字段成员的某个事件。这种情况应用非常广泛;因为它是Windows平台上默认的事件订阅和处理结构。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EventTest_WindowsFramework
{
class Program
{
static void Main(string[] args)
{
MyForm myForm = new MyForm();
myForm.ShowDialog();
}
}
class MyForm : Form
{
private Button button;
private TextBox textbox;
public MyForm()
{
button = new Button();
textbox = new TextBox();
this.Controls.Add(this.button);
this.Controls.Add(this.textbox);
this.button.Click += this.ButtonCliked;
this.button.Text = "Say hellow";
this.button.Top = 20;
}
private void ButtonCliked(object sender, EventArgs e)
{
this.textbox.Text = "Hello world";
}
}
}