Simplest way to achieve automatic notification of property change

后端 未结 6 570
时光说笑
时光说笑 2020-12-04 13:34

I know that there are solutions out there for implementing INotifyPropertyChanged, but none of them are as simple as: reference this library, create/add this attribute, done

6条回答
  •  时光说笑
    2020-12-04 13:55

    Try this https://github.com/Fody/PropertyChanged

    It will weave all properties of types that implement INotifyPropertyChanged and even handles dependencies.

    Your Code

    public class Person : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        public string GivenNames { get; set; }
        public string FamilyName { get; set; }
    
        public string FullName
        {
            get
            {
                return string.Format("{0} {1}", GivenNames, FamilyName);
            }
        }
    
    }
    

    What gets compiled

    public class Person : INotifyPropertyChanged
    {
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        private string givenNames;
        public string GivenNames
        {
            get { return givenNames; }
            set
            {
                if (value != givenNames)
                {
                    givenNames = value;
                    OnPropertyChanged("GivenNames");
                    OnPropertyChanged("FullName");
                }
            }
        }
    
        private string familyName;
        public string FamilyName
        {
            get { return familyName; }
            set 
            {
                if (value != familyName)
                {
                    familyName = value;
                    OnPropertyChanged("FamilyName");
                    OnPropertyChanged("FullName");
                }
            }
        }
    
        public string FullName
        {
            get
            {
                return string.Format("{0} {1}", GivenNames, FamilyName);
            }
        }    
    
        public void OnPropertyChanged(string propertyName)
        {
            var propertyChanged = PropertyChanged;
            if (propertyChanged != null)
            {
                propertyChanged(this, new PropertyChangedEventArgs(propertyName));    
            }
        }
    }
    

    Or you can use attributes for more fine grained control.

提交回复
热议问题