如何:实现属性更改通知

若要支持 OneWayTwoWay 绑定,使绑定目标属性能够自动反映绑定源的动态更改(例如,若要让用户编辑窗体时自动更新预览窗格),类需要提供正确的属性更改通知。 此示例演示如何创建实现 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 文本更新源时的控件。

另请参阅