下面簡單實現INotifyPropertyChanged接口this
using System; using System.ComponentModel; using System.Linq.Expressions; using System.Reflection; namespace LearnBinding.Model { public class ObservableObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public ObservableObject() { } protected PropertyChangedEventHandler PropertyChangedHandler { get; } protected virtual void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression) { if (PropertyChanged != null) { string propertyName = GetPropertyName<T>(propertyExpression); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } protected string GetPropertyName<T>(Expression<Func<T>> propertyExpression) { if (propertyExpression == null) { throw new ArgumentNullException("propertyExpression"); } MemberExpression memberExpression = propertyExpression.Body as MemberExpression; if (memberExpression == null) { throw new ArgumentException("Invalid argument", "propertyExpression"); } PropertyInfo propertyInfo = memberExpression.Member as PropertyInfo; if (propertyInfo == null) { throw new ArgumentException("Argument is not a property", "propertyExpression"); } return propertyInfo.Name; } } }