Cómo: Implementar la notificación de cambio de propiedad

Actualización: noviembre 2007

Para que en los enlaces OneWay o TwoWay se permita que las propiedades de destino de enlace reflejen automáticamente los cambios dinámicos del origen de enlace (por ejemplo, para que el panel de vista previa se actualice automáticamente cuando el usuario edite un formulario), es preciso que la clase proporcione las notificaciones apropiadas de cambio de propiedad. En este ejemplo se muestra cómo crear una clase que implementa INotifyPropertyChanged.

Ejemplo

Para implementar INotifyPropertyChanged, es preciso declarar el evento PropertyChanged y crear el método OnPropertyChanged. A continuación, para cada propiedad cuyas notificaciones de cambio desee habilitar, deberá llamar a OnPropertyChanged cada vez que se actualice la propiedad.

Imports System.ComponentModel

' This class implements INotifyPropertyChanged
' to support one-way and two-way bindings
' (such that the UI element updates when the source
' has been changed dynamically)
Public Class Person
    Implements INotifyPropertyChanged

    Private personName As String

    Sub New()
    End Sub

    Sub New(ByVal Name As String)
        Me.personName = Name
    End Sub

    ' Declare the event
    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Public Property Name() As String
        Get
            Return personName
        End Get
        Set(ByVal value As String)
            personName = value
            ' Call OnPropertyChanged whenever the property is updated
            OnPropertyChanged("Name")
        End Set
    End Property

    ' Create the OnPropertyChanged method to raise the event
    Protected Sub OnPropertyChanged(ByVal name As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
    End Sub

End Class
using System.ComponentModel;

namespace SDKSample
{
  // This class implements INotifyPropertyChanged
  // to support one-way and two-way bindings
  // (such that the UI element updates when the source
  // has been changed dynamically)
  public class Person : INotifyPropertyChanged
  {
      private string name;
      // Declare the event
      public event PropertyChangedEventHandler PropertyChanged;

      public Person()
      {
      }

      public Person(string value)
      {
          this.name = value;
      }

      public string PersonName
      {
          get { return name; }
          set
          {
              name = value;
              // Call OnPropertyChanged whenever the property is updated
              OnPropertyChanged("PersonName");
          }
      }

      // Create the OnPropertyChanged method to raise the event
      protected void OnPropertyChanged(string name)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
              handler(this, new PropertyChangedEventArgs(name));
          }
      }
  }
}

Para ver un ejemplo de utilización de la clase Person para admitir los enlaces TwoWay, consulte Cómo: Controlar cuándo el texto de TextBox actualiza el origen.

Para obtener el ejemplo completo, vea Ejemplo Simple Binding.

Vea también

Conceptos

Información general sobre orígenes de enlaces

Información general sobre el enlace de datos

Otros recursos

Ejemplos de enlace de datos

Temas "Cómo..." sobre enlace de datos