tomlev

OnPropertyChanged with lambda + anonymous type

May 23rd, 2012
54
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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(() => new { 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(() => new { 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<T>(Expression<Func<T>> propertySelector)
  40.     {
  41.         foreach (string name in ExtractPropertyNames(propertySelector))
  42.         {
  43.             OnPropertyChanged(name);
  44.         }
  45.     }
  46.    
  47.     protected static string[] ExtractPropertyNames<T>(Expression<Func<T>> propertySelector)
  48.     {
  49.         var memberExpr = propertySelector.Body as MemberExpression;
  50.         if (memberExpr != null)
  51.             return new[] { memberExpr.Member.Name };
  52.        
  53.         // Handle anonymous type
  54.         var newExpr = propertySelector.Body as NewExpression;
  55.         if (newExpr != null)
  56.         {
  57.             var names = new List<string>();
  58.             foreach (var arg in newExpr.Arguments)
  59.             {
  60.                 memberExpr = arg as MemberExpression;
  61.                 if (arg == null)
  62.                     throw new ArgumentException("Only member access expressions are supported in anonymous types");
  63.                 names.Add(memberExpr.Member.Name);
  64.             }
  65.             return names.ToArray();
  66.         }
  67.        
  68.         throw new ArgumentException("Only member access expressions and anonymous type creation are supported");
  69.     }
  70. }
RAW Paste Data