C# 如何在C中创建属性更改事件和更改事件#
我创建了一个属性C# 如何在C中创建属性更改事件和更改事件#,c#,events,event-handling,C#,Events,Event Handling,我创建了一个属性 public int PK_ButtonNo { get { return PK_ButtonNo; } set { PK_ButtonNo = value; } } 现在,我想将事件添加到此属性,以进行值更改和更改 我写了两个事件。在这里,我希望两个事件都包含更改的值和更改的值 i、 e 当用户实现事件时。他必须拥有e.OldValue,e.NewValue public event EventHandler ButtonNumberChanging; p
public int PK_ButtonNo
{
get { return PK_ButtonNo; }
set { PK_ButtonNo = value; }
}
现在,我想将事件添加到此属性,以进行值更改和更改
我写了两个事件。在这里,我希望两个事件都包含更改的值和更改的值
i、 e
当用户实现事件时。他必须拥有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;
和财产:
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”等。发布它!让更好的解决方案获胜!(:@Nathan:是的,你能做到。谢谢Nissim和所有努力提供解决方案的人。@Shantanu我并不担心,Nissim的解决方案是一模一样的。你在叫“PK_ButtonNo”内部!这将导致StackOverflow异常。添加一个私有成员并让属性访问itOk Nissim:我没有注意到。谢谢
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);
}
}
}