点击这里给我发消息 点击这里给我发消息

c# 实现自定义属性改变触发自定义事件

添加时间:2013-12-7
    相关阅读: Windows

代码,内含说明(界面是两个文本框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; }
}

 

 

咨询热线:020-85648757 85648755 85648616 0755-27912581 客服:020-85648756 0755-27912581 业务传真:020-32579052
广州市网景网络科技有限公司 Copyright◎2003-2008 Veelink.com. All Rights Reserved.
广州商务地址:广东省广州市黄埔大道中203号(海景园区)海景花园C栋501室
= 深圳商务地址:深圳市宝源路华丰宝源大厦606
研发中心:广东广州市天河软件园海景园区 粤ICP备05103322号 工商注册