NotificationObject.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.ComponentModel;
  3. using System.Linq.Expressions;
  4. using System.Runtime.CompilerServices;
  5. namespace Flyinsono.Client.Test
  6. {
  7. /// <summary>
  8. /// Implementation of INotifyPropertyChanged
  9. /// </summary>
  10. public abstract class NotificationObject : INotifyPropertyChanged
  11. {
  12. /// <summary>
  13. /// Property change handler
  14. /// </summary>
  15. public event PropertyChangedEventHandler PropertyChanged;
  16. protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
  17. {
  18. PropertyChangedEventHandler handler = PropertyChanged;
  19. if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
  20. }
  21. protected void OnPropertyChanged<T>(Expression<Func<T>> propertyExpression)
  22. {
  23. var propertyName = GetPropertyName(propertyExpression);
  24. OnPropertyChanged(propertyName);
  25. }
  26. protected void OnPropertyChanged(params Expression<Func<object>>[] propertyExpressions)
  27. {
  28. foreach (var expression in propertyExpressions)
  29. {
  30. OnPropertyChanged<object>(expression);
  31. }
  32. }
  33. private static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
  34. {
  35. if (propertyExpression == null)
  36. {
  37. throw new ArgumentNullException("propertyExpression");
  38. }
  39. var memberExpression = propertyExpression.Body as MemberExpression;
  40. if (memberExpression != null)
  41. {
  42. return memberExpression.Member.Name;
  43. }
  44. var unaryExpression = propertyExpression.Body as UnaryExpression;
  45. if (unaryExpression != null)
  46. {
  47. var memberInfo = (MemberExpression)unaryExpression.Operand;
  48. return memberInfo.Member.Name;
  49. }
  50. return string.Empty;
  51. }
  52. }
  53. }