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

标签 c# events event-handling

我创建了一个属性

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/

相关文章:

events - 单选按钮更改事件 JavaFx

javascript - Angular 2 事件处理和自定义事件

c# - 为具有不同事件处理程序委托(delegate)的多个控件实现单个事件处理程序

c# - 检索 x :Name or x:Key from Brush

c# - 在 C# 中引发忽略处理程序引发的异常的事件

javascript - 'event' 是 JavaScript 中的保留字吗?

jquery - jQuery 如何监听被触发的 DOM 事件?

c# - 如何正确使用 IReadOnlyDictionary?

c# - 如何将类方法的值返回到调用它的相应页面

javascript - 使用 document.attachEvent 时检查事件目标