萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> asp.net編程 >> c# 實現自定義屬性改變觸發自定義事件

c# 實現自定義屬性改變觸發自定義事件

代碼,內含說明(界面是兩個文本框textbox1,textbox2,和一個button1,界面的Load事件,button的click事件)
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);//加載事件


}


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;
}
}


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();//啟動事件
}


}
}


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; }
}

copyright © 萬盛學電腦網 all rights reserved