Implementing INotifyPropertyChanged - does a better way exist?

前端 未结 30 3369
感情败类
感情败类 2020-11-21 05:23

Microsoft should have implemented something snappy for INotifyPropertyChanged, like in the automatic properties, just specify {get; set; notify;} I

30条回答
  •  梦谈多话
    2020-11-21 05:36

    An idea using reflection:

    class ViewModelBase : INotifyPropertyChanged {
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        bool Notify(MethodBase mb, ref T oldValue, T newValue) {
    
            // Get Name of Property
            string name = mb.Name.Substring(4);
    
            // Detect Change
            bool changed = EqualityComparer.Default.Equals(oldValue, newValue);
    
            // Return if no change
            if (!changed) return false;
    
            // Update value
            oldValue = newValue;
    
            // Raise Event
            if (PropertyChanged != null) {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }//if
    
            // Notify caller of change
            return true;
    
        }//method
    
        string name;
    
        public string Name {
            get { return name; }
            set {
                Notify(MethodInfo.GetCurrentMethod(), ref this.name, value);
            }
        }//method
    
    }//class
    

提交回复
热议问题