Implementing INotifyPropertyChanged - does a better way exist?

前端 未结 30 2621
感情败类
感情败类 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:29

    As of .Net 4.5 there is finally an easy way to do this.

    .Net 4.5 introduces a new Caller Information Attributes.

    private void OnPropertyChanged([CallerMemberName]string caller = null) {
         // make sure only to call this if the value actually changes
    
         var handler = PropertyChanged;
         if (handler != null) {
            handler(this, new PropertyChangedEventArgs(caller));
         }
    }
    

    It's probably a good idea to add a comparer to the function as well.

    EqualityComparer.Default.Equals
    

    More examples here and here

    Also see Caller Information (C# and Visual Basic)

提交回复
热议问题