簡體   English   中英

如何在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.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);
    }
}

實施此事件時,如何獲取更改后的值和更改后的值。

將以下類添加到您的項目中:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM