操作說明:實作屬性變更通知
若要支援 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 文字更新來源的時機。