Advertisement
tomlev

OnPropertyChanged with multiple lambdas

May 23rd, 2012
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.77 KB | None | 0 0
  1. class MyClass : INotifyPropertyChanged
  2. {
  3.     private string _foo;
  4.     public string Foo
  5.     {
  6.         get { return _foo; }
  7.         set
  8.         {
  9.             _foo = value;
  10.             OnPropertyChanged(() => Foo, () => Baz);
  11.         }
  12.     }
  13.    
  14.     private int _bar;
  15.     public int Bar
  16.     {
  17.         get { return _bar; }
  18.         set
  19.         {
  20.             _bar = value;
  21.             OnPropertyChanged(() => Bar, () => Baz);
  22.         }
  23.     }
  24.    
  25.     public string Baz
  26.     {
  27.         get { return _foo + _bar; }
  28.     }
  29.  
  30.     public event PropertyChangedEventHandler PropertyChanged;
  31.    
  32.     protected virtual void OnPropertyChanged(string propertyName)
  33.     {
  34.         var handler = PropertyChanged;
  35.         if (handler != null)
  36.             handler(this, new PropertyChangedEventArgs(propertyName));
  37.     }
  38.    
  39.     protected void OnPropertyChanged(params Expression<Func<object>>[] propertySelectors)
  40.     {
  41.         foreach (var expr in propertySelectors)
  42.         {
  43.             OnPropertyChanged(ExtractPropertyName(expr));
  44.         }
  45.     }
  46.    
  47.     protected static string ExtractPropertyName(Expression<Func<object>> propertySelector)
  48.     {
  49.         var memberExpr = propertySelector.Body as MemberExpression;
  50.         if (memberExpr == null)
  51.         {
  52.             // Handle boxing of value types
  53.             var boxingExpr = propertySelector.Body as UnaryExpression;
  54.             if (boxingExpr != null && boxingExpr.NodeType == ExpressionType.Convert && boxingExpr.Type == typeof(object))
  55.             {
  56.                 memberExpr = boxingExpr.Operand as MemberExpression;
  57.             }
  58.         }
  59.         if (memberExpr != null)
  60.             return memberExpr.Member.Name;
  61.         throw new ArgumentException("Only member access expressions are supported");
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement