INotifyPropertyChanged for model and viewmodel

后端 未结 1 1650
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-24 22:31

I am currently away from home (and will be for a few more weeks) and only have a tablet - therefore, I have no access to Visual Studio to test what I\'m trying to learn - the

相关标签:
1条回答
  • 2021-01-24 23:02

    No, they don't have to share anything. However the implementation of INotifyPropertyChanged is some lines of code, so we usually made a base class for models - like BaseModel or BaseViewModel which implemented INotifyPropertyChanged.

    The implementations are generally specific to the version of C# language you use (the older ones works in the newer version of language).

    Look here: http://jesseliberty.com/2012/06/28/c-5making-inotifypropertychanged-easier/

    but instead of having the Employee class to implement the INotifyPropertyChanged, you can implement it in a base class

    public class BaseViewModel : INotifyPropertyChanged
    {
    
        public event PropertyChangedEventHandler PropertyChanged;
        protected void RaisePropertyChanged([CallerMemberName] string caller = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(caller));
            }
        }
    }
    

    and then the Employee class from the blog should look like this

    public class Employee : BaseViewModel
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                RaisePropertyChanged();
            }
        }
    }
    

    this is for C# 5 (the .Net 4.5 - the one which does not run on Windows XP)

    0 讨论(0)
提交回复
热议问题