Share via


방법: 속성 변경 알림 구현

업데이트: 2007년 11월

사용자가 폼을 편집할 때 미리 보기 창이 자동으로 업데이트되도록 하는 등 바인딩 대상 속성에 바인딩 소스의 동적 변경 내용이 자동으로 반영되도록 OneWay 또는 TwoWay 바인딩을 지원하려면 사용자 클래스에서 적절한 속성 변경 알림을 제공해야 합니다. 이 예제에서는 INotifyPropertyChanged를 구현하는 클래스를 만드는 방법을 보여 줍니다.

예제

INotifyPropertyChanged를 구현하려면 PropertyChanged 이벤트를 선언하고 OnPropertyChanged 메서드를 만들어야 합니다. 그런 다음 변경 알림을 제공할 각 속성에 대해 해당 속성이 업데이트될 때마다 OnPropertyChanged를 호출합니다.

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

Person 클래스를 사용하여 TwoWay 바인딩을 지원하는 방법에 대한 예제를 보려면 방법: TextBox 텍스트의 소스를 업데이트하는 시점 제어를 참조하십시오.

전체 샘플을 보려면 단순 바인딩 샘플을 참조하십시오.

참고 항목

개념

바인딩 소스 개요

데이터 바인딩 개요

기타 리소스

데이터 바인딩 샘플

데이터 바인딩 방법 항목