Implementing INotifyPropertyChanged - does a better way exist?

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

    Another combined solution is using StackFrame:

    public class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected void Set(ref T field, T value)
        {
            MethodBase method = new StackFrame(1).GetMethod();
            field = value;
            Raise(method.Name.Substring(4));
        }
    
        protected void Raise(string propertyName)
        {
            var temp = PropertyChanged;
            if (temp != null)
            {
                temp(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

    Usage:

    public class TempVM : BaseViewModel
    {
        private int _intP;
        public int IntP
        {
            get { return _intP; }
            set { Set(ref _intP, value); }
        }
    }
    

提交回复
热议问题