天天看點

wpf 屬性變更通知接口 INotifyPropertyChanged

在wpf中将控件綁定到對象的屬性時, 當對象的屬性發生改變時必須通知控件作出相應的改變, 是以此對象需要實作 INotifyPropertyChanged 接口

例1: (注意:從 .Net 4.5 才開始支援此特性)

//實作屬性變更通知接口 INotifyPropertyChanged
    public class TestA : INotifyPropertyChanged
    {
        public long ID { get; set; }

        private string name;
        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                if (value != this.name)
                {
                    this.name = value;
                    //調用屬性變更通知方法
                    NotifyPropertyChanged();
                }
            }
        }

        // INotifyPropertyChanged 接口成員
        public event PropertyChangedEventHandler PropertyChanged;
        //此方法在每個屬性的set中調用
        //在可選參數propertyName上應用CallerMemberName特性
        //調用此方法時,調用方的資訊将替換為可選參數的參數,即在set中調用此方法,propertyName="目前屬性的名稱"
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }      

 例2:(.net 4.0)

//實作屬性變更通知接口 INotifyPropertyChanged
    public class TestA : INotifyPropertyChanged
    {
        public long ID { get; set; }

        private string name;
        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                if (value != this.name)
                {
                    this.name = value;
                    //調用屬性變更通知方法,參數為"屬性名稱"
                    NotifyPropertyChanged("Name");
                }
            }
        }

        // INotifyPropertyChanged 接口成員
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

    }      

轉載于:https://www.cnblogs.com/gmcn/p/5882026.html