방법: 속성 변경 알림 구현

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

예제

INotifyPropertyChanged를 구현하려면 PropertyChanged 이벤트를 선언하고 OnPropertyChanged 메서드를 만들어야 합니다. 그런 다음 변경 알림이 필요한 각 속성이 업데이트될 때마다 OnPropertyChanged를 호출합니다.

using System.ComponentModel;
using System.Runtime.CompilerServices;

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

      // Create the OnPropertyChanged method to raise the event
      // The calling member's name will be used as the parameter.
      protected void OnPropertyChanged([CallerMemberName] string name = null)
      {
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
      }
  }
}
Imports System.ComponentModel
Imports System.Runtime.CompilerServices

' 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()
        End Set
    End Property

    ' Create the OnPropertyChanged method to raise the event
    ' Use the name of the member that called this method in place of name
    Protected Sub OnPropertyChanged(<CallerMemberName> Optional name As String = Nothing)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
    End Sub

End Class

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

참고 항목