Friday, March 28, 2014

INotifyPropertyChanged in .Net 4.5 - CallerMemberName

We are all pretty used to writing our property changed notification something like this.
   public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                if (value.Equals(_isBusy)) return;
                _isBusy = value;
                RaisePropertyChanged("IsBusy");
            }
        }
   private bool _isBusy;
or better yet, make it re-factor friendly using Linq
   public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                if (value.Equals(_isBusy)) return;
                _isBusy = value;
                RaisePropertyChanged(() => IsBusy);
            }
        }
   private bool _isBusy;

What if we could just do something like this...
   public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                if (value.Equals(_isBusy)) return;
                _isBusy = value;
                NotifyChanged();
            }
        }
   private bool _isBusy;
Now with .Net 4.5 the above is possible.  Here is a basic implementation of ObservableObject with the new .Net 4.5 CallerMemberName attribute.
    /// <summary> Base observable object class. </summary>
    public abstract class ObservableObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public delegate void PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e);

        /// <summary> Notify property has changed </summary>
        /// <param name="propertyName">String property name, if not provided, will be picked up from calling member</param>
        protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }

No comments:

Post a Comment