Get notified when properties change in the Model

后端 未结 4 862
-上瘾入骨i
-上瘾入骨i 2021-01-27 05:16

There seems to be conflicting thoughts on whether INotifyPropertyChanged should be implemented in the Model or not. I think that it should be implemented in the Vie

4条回答
  •  被撕碎了的回忆
    2021-01-27 05:47

    Save for the typos you pretty much have it ;)

    All you would need to add is your constructor and property definitions:

    public class PersonViewModel : INotifyPropertyChanged
    {
        Person _person;
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected virtual void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                handler(this, e);
            }
        }
    
        public PersonViewModel(Person person)
        {
            _person = person;
        }
    
        public int Age
        {
            get
            {
                return _person.Age;
            }
            set
            {
                _person.Age = value;
                OnPropertyChanged("Age");
            }
        }
    }
    

    If you have a choice, I would definitely recommend implementing INotifyPropertyChanged in the Model because you won't havae to worry about translating Models to ViewModels and back.

    But if you can't, see above :)

提交回复
热议问题