Implementing INotifyPropertyChanged - does a better way exist?

前端 未结 30 2610
感情败类
感情败类 2020-11-21 05:23

Microsoft should have implemented something snappy for INotifyPropertyChanged, like in the automatic properties, just specify {get; set; notify;} I

30条回答
  •  难免孤独
    2020-11-21 05:41

    I created an Extension Method in my base Library for reuse:

    public static class INotifyPropertyChangedExtensions
    {
        public static bool SetPropertyAndNotify(this INotifyPropertyChanged sender,
                   PropertyChangedEventHandler handler, ref T field, T value, 
                   [CallerMemberName] string propertyName = "",
                   EqualityComparer equalityComparer = null)
        {
            bool rtn = false;
            var eqComp = equalityComparer ?? EqualityComparer.Default;
            if (!eqComp.Equals(field,value))
            {
                field = value;
                rtn = true;
                if (handler != null)
                {
                    var args = new PropertyChangedEventArgs(propertyName);
                    handler(sender, args);
                }
            }
            return rtn;
        }
    }
    

    This works with .Net 4.5 because of CallerMemberNameAttribute. If you want to use it with an earlier .Net version you have to change the method declaration from: ...,[CallerMemberName] string propertyName = "", ... to ...,string propertyName, ...

    Usage:

    public class Dog : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        string _name;
    
        public string Name
        {
            get { return _name; }
            set
            {
                this.SetPropertyAndNotify(PropertyChanged, ref _name, value);
            }
        }
    }
    

提交回复
热议问题