知识大全 c# 实现自定义属性改变触发自定义事件

Posted 事件

篇首语:做好自己,不为别人的欣赏而存在,却为着自己的特色而活着。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 c# 实现自定义属性改变触发自定义事件相关的知识,希望对你有一定的参考价值。

  代码 内含说明(界面是两个文本框textbox textbox 和一个button 界面的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 Form : Form public Form () InitializeComponent();

   //CustomClass cc = new CustomClass( "Lee");//测试属性值不变化的情况 CustomClass cc = new CustomClass();//空构造函数 一边测试属性值改变

   private void Form _Load(object sender EventArgs e) cc Changed += new CustomClass ChangedEventHandler(cc_Changed);//加载事件

  

   private void button _Click(object sender EventArgs e) cc Cid = ; cc Cname = "Lee";//给CustomClass的属性赋值 赋值是引发事件 string str = cc Cid ToString() + cc Cname; MessageBox Show(str);

   private void cc_Changed()//事件 textBox Text = cc Cid ToString(); textBox 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;

cha138/Article/program/net/201311/14416

相关参考