Implementing INotifyPropertyChanged - does a better way exist?

前端 未结 30 2728
感情败类
感情败类 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:46

    Another Idea...

     public class ViewModelBase : INotifyPropertyChanged
    {
        private Dictionary _propertyStore = new Dictionary();
        protected virtual void SetValue(T value, [CallerMemberName] string propertyName="") {
            _propertyStore[propertyName] = value;
            OnPropertyChanged(propertyName);
        }
        protected virtual T GetValue([CallerMemberName] string propertyName = "")
        {
            object ret;
            if (_propertyStore.TryGetValue(propertyName, out ret))
            {
                return (T)ret;
            }
            else
            {
                return default(T);
            }
        }
    
        //Usage
        //public string SomeProperty {
        //    get { return GetValue();  }
        //    set { SetValue(value); }
        //}
    
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            var temp = PropertyChanged;
            if (temp != null)
                temp.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    

提交回复
热议问题