Posted By

nimast on 03/05/11


Tagged

WPF INotifyPropertyChanged c#


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

cybermax


NotifyPropertyChanged


 / Published in: C#
 

The only way i know to create a normal "fire property changed" method that is still efficient yet strongly typed. The other common pattern uses run time checking and uses the TyepDescriptor for the current type to check for property existence - a much less elegant solution imho.

  1. public class PresenterBase : INotifyPropertyChanged
  2. {
  3. private string _myProperty;
  4. public string MyProperty
  5. {
  6. get
  7. {
  8. return _myProperty;
  9. }
  10. set
  11. {
  12. _myProperty = value;
  13. OnPropertyChanged(() => MyProperty);
  14. }
  15. }
  16.  
  17. protected virtual void OnPropertyChanged<T>(Expression<Func<T>> propertyEvaluator)
  18. {
  19. var lambda = propertyEvaluator as LambdaExpression;
  20. var member = lambda.Body as MemberExpression;
  21. var handler = PropertyChanged;
  22. if (handler != null)
  23. {
  24. handler(this, new PropertyChangedEventArgs(member.Member.Name));
  25. }
  26. }
  27.  
  28. #region INotifyPropertyChanged Members
  29.  
  30. public event PropertyChangedEventHandler PropertyChanged;
  31.  
  32. #endregion
  33. }

Report this snippet  

You need to login to post a comment.