如何在C#中创建属性更改和更改事件的事件

时间:2010-08-24 08:21:35

标签: c# events event-handling

我创建了一个属性

public int PK_ButtonNo 
{
    get { return PK_ButtonNo; }
    set { PK_ButtonNo = value; }
}

现在我想向此属性添加事件以进行值更改和更改。

我写了两个事件。在这里,我希望两个事件都包含更改的值以及更改的值。

当用户实现该事件时。他必须e.OldValuee.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);
    }
}

当我实现此事件时,如何获取更改的值和更改的值。

1 个答案:

答案 0 :(得分:6)

将以下类添加到项目中:

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”等...