1. 程式人生 > >WPF 自定義NotifyPropertyChanged

WPF 自定義NotifyPropertyChanged

prot hang null 值變化 his protected change dev rgs

技術分享圖片 技術分享圖片
    /// <summary>
    /// 實現了屬性更改通知的基類
    /// </summary>
    public class BaseNotifyPropertyChanged : System.ComponentModel.INotifyPropertyChanged
    {
        /// <summary>
        /// 屬性值變化時發生
        /// </summary>
        /// <param name="propertyName"></param>
        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }

        /// <summary>
        /// 屬性值變化時發生
        /// </summary>
        /// <param name="propertyName"></param>
        protected virtual void OnPropertyChanged<T>(Expression<Func<T>> propertyExpression)
        {
            var propertyName = (propertyExpression.Body as MemberExpression).Member.Name;
            this.OnPropertyChanged(propertyName);
        }

        public virtual event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
    }
技術分享圖片

使用時繼承此類,然後在VM中的屬性get使用:OnPropertyChanged(()=>PropertyName) ??難道不是應該Set

WPF 自定義NotifyPropertyChanged