Code, containing instructions (interface is two text box 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")//test property value does not change
Customclass cc = new Customclass ()//empty constructor, while testing property value changes
private void Form1_Load (object sender, EventArgs e)
{
Cc. Changed + + new Customclass.changedeventhandler (cc_changed);//Load Event
}
private void Button1_Click (object sender, EventArgs e)
{
Cc. Cid = 1;
Cc. Cname = "Lee"//To assign a value to the Customclass property, which is to raise an 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 ();//define Delegate
Public event Changedeventhandler changed;//defining events
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)//Here is the processing of text changes
{
_cid = value;
OnChanged ()//Start Event
}
}
}
public string Cname
{
Get
{
return _cname;
}
Set
{
if (_cname!= value)
{
_cname = value;
OnChanged ();
}
}
}
}
}
The following is an example of a very classical property value change that triggers a custom event on the Web, as follows;
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>
Generic 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;}
}