2010-08-24 25 views
5

creé una propiedadCómo crear un evento en el cambio de propiedad y cambio de eventos en C#

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

Ahora quiero añadir eventos a esta propiedad por valor cambiante y cambiado.

Escribí dos eventos. Aquí quiero que ambos eventos contengan valores cambiantes y valores modificados.

es decir

Cuando el usuario implementa el evento. Él debe tener 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); 
    } 
} 

¿Cómo puedo obtener el valor de cambio y el valor cambiado cuando implemente este evento.

+0

Usted están llamando "PK_ButtonNo" dentro de sí mismo! esto causará una excepción de StackOverflow. Añadir un miembro privado y dejar que la propiedad acceda al mismo – Nissim

+0

Ok Nissim: No lo noté. Gracias –

Respuesta

6

Añadir la siguiente clase a su proyecto:

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; 
    } 
} 

Ahora, en su clase de añadir el cambio de declaración de evento:

public EventHandler<ValueChangingEventArgs> ButtonNumberChanging; 

Agregue el siguiente miembro (para evitar la excepción stackoverflow):

private int m_pkButtonNo; 

y la propiedad:

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); 
     } 
    } 
} 

El "Cancelar" propiedad permitirá al usuario cancelar la operación de cambio, esto es un estándar en una serie de eventos-x ing, tales como "FormClosing", "Validación", etc ...

+0

¡Me ganaste! ¡Casi terminé de tipear! –

+1

¡Publiquelo! y deja que la mejor solución gane! (: – Nissim

+0

@ Nathan: Sí, puedes hacerlo a Nissim y a todos aquellos que se esforzaron por brindar una solución. –

Cuestiones relacionadas