Search code examples
c#inotifypropertychangedautomatic-properties

How to get OnPropertyChanging event when use NotifyPropertyWeaver?


I use NotifyPropertyWeaverMsBuildTask to handle NotifyPropertyChanged for automatic properties. I know OnPropertyChanged() method rise when Property value is changed. But when this method is called value of property is changed and old value is lost. Is there any way to get old value?

tanx.


Solution

  • If you want to use the old value inside the OnPropertyChanged then write it like this

    public void OnPropertyChanged(string propertyName, object before, object after)
    

    Then if your code looks like this

    public class Person : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        public string Name { get; set; }
    
        public void OnPropertyChanged(string propertyName, object before, object after)
        {
            // do something with before/after
            var propertyChanged = PropertyChanged;
            if (propertyChanged != null)
            {
                propertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

    This will be injected

    public class Person : INotifyPropertyChanged
    {
        private string name;
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        public string Name
        {
            get { return name; }
            set
            {
                object before = Name;
                name = value;
                OnPropertyChanged("Name", before, Name);
            }
        }
    
        public void OnPropertyChanged(string propertyName, object before, object after)
        {            
            // do something with before/after
            var propertyChanged = PropertyChanged;
            if (propertyChanged != null)
            {
                propertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

    More information is available here https://github.com/SimonCropp/NotifyPropertyWeaver/wiki/BeforeAfter

    Does this meet your requirements?