代碼
using System;
using System
using System
using System
using System
using System
using System
using System
namespace Test
{
public partial class Form
{
public Form
{
InitializeComponent();
}
//CustomClass cc = new CustomClass(
CustomClass cc = new CustomClass();//空構造函數
private void Form
{
cc
}
private void button
{
cc
cc
string str = cc
MessageBox
}
private void cc_Changed()//事件
{
textBox
textBox
}
}
public class CustomClass
{
public delegate void ChangedEventHandler();//定義委托
public event ChangedEventHandler Changed;//定義事件
private int _Cid;
private string _Cname;
public CustomClass()
{
}
public CustomClass(int cCid
{
this
this
}
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"
if (this
{
this
if (e
}
_myProperty = (int)e
if (this
{
this
}
}
}
}
}
/// <summary>
/// 通用的類
/// </summary>
public class PropertyChagedEventArgs : EventArgs
{
public PropertyChagedEventArgs(string propertyName
{
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; }
}
From:http://tw.wingwit.com/Article/program/net/201311/14416.html