c#

位置:IT落伍者 >> c# >> 浏览文章

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


发布日期:2020年01月27日
 
c# 实现自定义属性改变触发自定义事件

代码内含说明(界面是两个文本框textboxtextbox和一个button界面的Load事件button的click事件)
using System;
using SystemCollectionsGeneric;
using SystemComponentModel;
using SystemData;
using SystemDrawing;
using SystemLinq;
using SystemText;
using SystemWindowsForms;


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)
{
ccChanged += new CustomClassChangedEventHandler(cc_Changed);//加载事件


}


private void button_Click(object sender EventArgs e)
{
ccCid = ;
ccCname = "Lee";//给CustomClass的属性赋值赋值是引发事件
string str = ccCidToString() + ccCname;
MessageBoxShow(str);
}


private void cc_Changed()//事件
{
textBoxText = ccCidToString();
textBoxText = ccCname;
}
}


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 (thisMyPropertyChanging != null)
{
thisMyPropertyChanging(this e);
if (eCancel) return;
}
_myProperty = (int)eNewValue;
if (thisMyPropertyChanged != null)
{
thisMyPropertyChanged(this e);
}
}
}
}


}

/// <summary>
/// 通用的类
/// </summary>
public class PropertyChagedEventArgs : EventArgs
{
public PropertyChagedEventArgs(string propertyNameobject oldValueobject 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; }
}

上一篇:在.NET开发中灵活使用TreeView控件

下一篇:Visual Studio 2008常用小技巧