熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

c# 實現自定義屬性改變觸發自定義事件

2022-06-13   來源: .NET編程 

  代碼內含說明(界面是兩個文本框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; }
}


From:http://tw.wingwit.com/Article/program/net/201311/14416.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.