我创建了一个属性
public int PK_ButtonNo
{
get { return PK_ButtonNo; }
set { PK_ButtonNo = value; }
}
现在我想向此属性添加事件以更改值和已更改。
我写了两个事件。在这里,我希望这两个事件都包含变化的值以及变化的值。
即
当用户实现事件时。他一定有e.OldValue
, e.NewValue
public event EventHandler ButtonNumberChanging;
public event EventHandler ButtonNumberChanged;
public int PK_ButtonNo
{
get { return PK_ButtonNo; }
private set
{
if (PK_ButtonNo == value)
return;
if (ButtonNumberChanging != null)
this.ButtonNumberChanging(this,null);
PK_ButtonNo = value;
if (ButtonNumberChanged != null)
this.ButtonNumberChanged(this,null);
}
}
我在实现这个事件的时候,如何获取变化的值和变化的值。
最佳答案
将以下类添加到您的项目中:
public class ValueChangingEventArgs : EventArgs
{
public int OldValue{get;private set;}
public int NewValue{get;private set;}
public bool Cancel{get;set;}
public ValueChangingEventArgs(int OldValue, int NewValue)
{
this.OldValue = OldValue;
this.NewValue = NewValue;
this.Cancel = false;
}
}
现在,在您的类中添加更改事件声明:
public EventHandler<ValueChangingEventArgs> ButtonNumberChanging;
添加如下成员(防止stackoverflow异常):
private int m_pkButtonNo;
和属性:
public int PK_ButtonNo
{
get{ return this.m_pkButtonNo; }
private set
{
if (ButtonNumberChanging != null)
ValueChangingEventArgs vcea = new ValueChangingEventArgs(PK_ButtonNo, value);
this.ButtonNumberChanging(this, vcea);
if (!vcea.Cancel)
{
this.m_pkButtonNo = value;
if (ButtonNumberChanged != null)
this.ButtonNumberChanged(this,EventArgs.Empty);
}
}
}
“Cancel”属性将允许用户取消更改操作,这是 x-ing 事件中的标准,例如“FormClosing”、“Validating”等...
关于c# - 如何在 C# 中创建属性更改和更改事件的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3554643/