共用方式為


HOW TO:實作屬性變更通知

更新:2007 年 11 月

若要支援 OneWayTwoWay 繫結而讓繫結目標屬性能自動反映繫結來源的動態變更 (例如,當使用者編輯表單時自動更新預覽窗格),您的類別就必須提供適當的屬性變更通知。本範例顯示如何建立可實作 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 繫結的範例,請參閱 HOW TO:TextBox 文字更新來源時控制

如需完整範例,請參閱簡單繫結範例

請參閱

概念

繫結來源概觀

資料繫結概觀

其他資源

資料繫結範例

資料繫結 HOW TO 主題