Code, containing instructions (the interface is two text boxes textbox1, textbox2, and a button1, interface Load event, button click event)
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"); // The test property value does not change
CustomClass cc = new CustomClass (); // empty constructor, while testing the attribute value change
Private void Form1_Load (object sender, EventArgs e)
{
Cc. Changed + = new CustomClass. ChangedEventHandler (cc_Changed); // load the event
}
Private void button#click (object sender, EventArgs e)
{
Cc. Cid = 1;
Cc. Cname = "Lee"; // assign a value to the CustomClass attribute, which triggers the event
String str = cc. Cid. ToString () + cc. Cname;
MessageBox. Show (str );
}
Private void cc_Changed () // event
{
TextBox1.Text = cc. Cid. ToString ();
TextBox2.Text = cc. Cname;
}
}
Public class CustomClass
{
Public delegate void ChangedEventHandler (); // defines the delegate
Public event ChangedEventHandler Changed; // defines the event
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) // processing when the text changes
{
_ Cid = value;
OnChanged (); // start the event
}
}
}
Public string Cname
{
Get
{
Return _ Cname;
}
Set
{
If (_ Cname! = Value)
{
_ Cname = value;
OnChanged ();
}
}
}
}
}
The following is an example of custom events caused by a classic attribute value change on the Internet;
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); // Initialization
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>
/// Common class
/// </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 ;}
}