以下说明可解释自定义的事件的自定义触发过程:
直接上代码,内含说明(界面是两个文本框textbox1,textbox2,和一个button1,界面的Load事件,button的click事件)
Form1 类(调用者端)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//CustomClass cc = new CustomClass(1, "Lee");//测试属性值不变化的情况
CustomClass cc = new CustomClass();//空构造函数,一边测试属性值改变
private void Form1_Load(object sender, EventArgs e)
{
cc.Changed += new CustomClass.ChangedEventHandler(cc_Changed);//调用者端订阅事件,为Changed事件提供了具体的事件函数cc_Changed
}
private void button1_Click(object sender, EventArgs e)
{
cc.Cid = 1;
cc.Cname = "Lee";//给CustomClass的属性赋值,赋值是引发事件
string str = cc.Cid.ToString() + cc.Cname;
MessageBox.Show(str);
}
private void
cc_Changed()//事件 注:被自定义事件绑定的事件函数
{
textBox1.Text = cc.Cid.ToString();
textBox2.Text = cc.Cname;
}
}
CustomClass类(事件定义端)
public class CustomClass
{
public delegate void ChangedEventHandler();//定义委托
public event ChangedEventHandler Changed;//定义事件
private int _Cid;
private string _Cname;
public CustomClass()
{
}
public CustomClass(int cCid, string cCname)
{
this._Cid = cCid;
this._Cname = cCname;
}
protected virtual void OnChanged()
{
if (Changed!=null)
{
Changed();
}
}
public int Cid
{
get
{
return _Cid;
}
set
{
if (_Cid!=value)//这里是文本改变时的处理
{
_Cid = value;
OnChanged();//启动事件
//注:变相的在更改值的过程中,调用了上面绑定的事件函数“cc_Changed()”,做到了对自定义事件的触发(cc_Changed()幻术的执行)
//需要明白:在当前类
CustomClass中,不能直接知道要执行的事件函数
//或者这么说:在定义自定义事件的类中,仅仅定义(1)事件本身及(2)可能在类中触发的事件调用(以本类而言,就是执行OnChanged()中的Changed()),具体调用哪个事件函数,是由“调用者端”提供的
}
}
}
public string Cname
{
get
{
return _Cname;
}
set
{
if (_Cname != value)
{
_Cname = value;
OnChanged();
}
}
}
}
}
以下是网上的一段非常经典的属性值改变引发自定义事件的例子,如下;
public class MyClass
{
public event EventHandler<PropertyChagedEventArgs> MyPropertyChanging;
public event EventHandler<PropertyChagedEventArgs> MyPropertyChanged;
private int _myProperty;
public int MyProperty
{
get { return _myProperty; }
set
{
if (value != _myProperty)
{
PropertyChagedEventArgs e = new PropertyChagedEventArgs("MyProperty", _myProperty, value);//初始化
if (this.MyPropertyChanging != null)
{
this.MyPropertyChanging(this, e);
if (e.Cancel) return;
}
_myProperty = (int)e.NewValue;
if (this.MyPropertyChanged != null)
{
this.MyPropertyChanged(this, e);
}
}
}
}
}
/// <summary>
/// 通用的类
/// </summary>
public class PropertyChagedEventArgs : EventArgs
{
public PropertyChagedEventArgs(string propertyName,object oldValue,object newValue)
{
PropertyName = propertyName;
OldValue = oldValue;
NewValue = newValue;
}
public bool Cancel { get; set; }
public string PropertyName { get; private set; }
public object OldValue { get; private set; }
public object NewValue { get; set; }
}