標籤:自訂事件 event 觸發
以下說明可解釋自訂的事件的自訂觸發過程:
直接上代碼,內含說明(介面是兩個文字框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; } }
通過c# 實現自訂屬性改變觸發自訂事件 ,理解自訂事件及其觸發過程