![](/img/trans.png)
[英]How to create a property changed event when the property has only a getter in C#
[英]How to create an event on property changing and changed event in C#
我创建了一个物业
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);
}
}
}
“取消”属性将允许用户取消更改操作,这是x-ing事件中的标准,例如“ FormClosing”,“ Validating”等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.