andrew4582

NotifyPropertyChangedBase

Nov 24th, 2012
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.41 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Linq.Expressions;
  6.  
  7. namespace Core
  8. {
  9.     #region Tests
  10.     public class TestNotifyPropertyChangedBase
  11.     {
  12.         public static void Test()
  13.         {
  14.             MyNotifyClass myclass = new MyNotifyClass();
  15.             myclass.PropertyChanged += (s, e) =>
  16.             {
  17.                 Debug.WriteLine("-----Property " + e.PropertyName + " Changed");
  18.             };
  19.  
  20.             myclass.FirstName = "Mary";
  21.             myclass.LastName = "Smith";
  22.             myclass.MiddleInitial = "B";
  23.             Debug.WriteLine(myclass.DisplayName);
  24.  
  25.             //married, last name changed
  26.             myclass.LastName = "Jones";
  27.             Debug.WriteLine(myclass.DisplayName);
  28.         }
  29.     }
  30.  
  31.     public class MyNotifyClass : NotifyPropertyChangedBase
  32.     {
  33.         public MyNotifyClass()
  34.         {
  35.             //raises the PropertyChanged when any of the FirstName, Middle, or Last Name is changed
  36.             UpdateOnProperty(() => DisplayName,
  37.                 () => FirstName, () => MiddleInitial, () => LastName);
  38.  
  39.             //update Initials when first or last name changes
  40.             UpdateOnProperty(() => Initials,
  41.                 () => FirstName, () => LastName);
  42.  
  43.             RegisterUpdateAction(() => Initials, () =>
  44.             {
  45.                 if (!string.IsNullOrEmpty(Initials))
  46.                     Debug.WriteLine("Initials Updated to " + Initials);
  47.             });
  48.         }
  49.  
  50.         string _firstName;
  51.         public string FirstName
  52.         {
  53.             get { return _firstName; }
  54.             set
  55.             {
  56.                 if (_firstName == value)
  57.                     return;
  58.                 _firstName = value;
  59.                 OnPropertyChanged(() => FirstName);
  60.             }
  61.         }
  62.  
  63.         string _middleInitial;
  64.         public string MiddleInitial
  65.         {
  66.             get { return _middleInitial; }
  67.             set
  68.             {
  69.                 if (_middleInitial == value)
  70.                     return;
  71.                 _middleInitial = value;
  72.                 OnPropertyChanged(() => MiddleInitial);
  73.             }
  74.         }
  75.  
  76.         string _lastName;
  77.         public string LastName
  78.         {
  79.             get { return _lastName; }
  80.             set
  81.             {
  82.                 if (_lastName == value)
  83.                     return;
  84.                 _lastName = value;
  85.                 OnPropertyChanged(() => LastName);
  86.             }
  87.         }
  88.  
  89.         public string Initials
  90.         {
  91.             get
  92.             {
  93.                 if (string.IsNullOrEmpty(FirstName) || string.IsNullOrEmpty(LastName))
  94.                     return null;
  95.                 if (FirstName.Length < 1 || LastName.Length < 1)
  96.                     return null;
  97.                 return string.Format("{0}{1}", FirstName.Substring(0, 1).ToUpper(), LastName.Substring(0, 1).ToUpper());
  98.             }
  99.         }
  100.  
  101.  
  102.         public string DisplayName
  103.         {
  104.             get
  105.             {
  106.                 return string.Format("{0} {1} {2}", FirstName, MiddleInitial, LastName);
  107.             }
  108.         }
  109.     }
  110.  
  111.     #endregion
  112.    
  113.     /// <summary>
  114.     /// Base class that implements <see cref="INotifyPropertyChanged"/>
  115.     /// </summary>
  116.     public abstract class NotifyPropertyChangedBase : INotifyPropertyChanged
  117.     {
  118.         readonly Dictionary<string, Action> registeredActions = new Dictionary<string, Action>();
  119.  
  120.         public event PropertyChangedEventHandler PropertyChanged;
  121.  
  122.         /// <summary>
  123.         /// Raise the PropertyChanged event if actions are registrered
  124.         /// </summary>
  125.         protected virtual void CheckRegeristeredAction(string propertyName)
  126.         {
  127.             Action updateAction = null;
  128.             if (registeredActions.TryGetValue(propertyName, out updateAction))
  129.             {
  130.                 if (updateAction != null)
  131.                     updateAction();
  132.             }
  133.         }
  134.  
  135.         /*
  136.          //Example
  137.          this.UpdateOnProperty(() => Title,
  138.            () => Name, () => MiddleInt, () => LastName);
  139.          */
  140.         /// <summary>
  141.         /// Updates a property when one or more of the specified properties are changed
  142.         /// </summary>
  143.         protected void UpdateOnProperty<T>(Expression<Func<T>> updateExpression, params Expression<Func<T>>[] propertyExpressions)
  144.         {
  145.             Action updateAction = () => OnPropertyChanged(updateExpression);
  146.  
  147.             foreach (var expression in propertyExpressions)
  148.             {
  149.                 MemberExpression memberExpression = (MemberExpression)expression.Body;
  150.                 string updatePropertyName = memberExpression.Member.Name;
  151.                 this.RegisterUpdateAction(expression, updateAction);
  152.             }
  153.         }
  154.  
  155.         /*
  156.          //Example
  157.          this.RegisterUpdateAction(() => Name, () =>
  158.          {
  159.             MessageBox.Show("Name Updated" + this.Name);
  160.          });
  161.          */
  162.         /// <summary>
  163.         /// Registers an action that is called when the provied property is changed
  164.         /// </summary>
  165.         protected void RegisterUpdateAction<T>(Expression<Func<T>> expression, Action updateAction)
  166.         {
  167.             string propertyName = GetPropertyName(expression);
  168.             registeredActions[propertyName] = updateAction;
  169.         }
  170.  
  171.  
  172.         /// <summary>
  173.         /// Fires the Notify Property Changed event
  174.         /// </summary>
  175.         protected void OnPropertyChanged<T>(Expression<Func<T>> expression)
  176.         {
  177.             string propertyName = GetPropertyName(expression);
  178.             OnPropertyChanged(propertyName);
  179.         }
  180.  
  181.         /// <summary>
  182.         /// Fires the Notify Property Changed event
  183.         /// </summary>
  184.         protected void OnPropertyChanged(string propertyName)
  185.         {
  186.  
  187.             PropertyChangedEventHandler handler = PropertyChanged;
  188.             if (handler != null)
  189.             {
  190.                 handler(this, new PropertyChangedEventArgs(propertyName));
  191.             }
  192.             CheckRegeristeredAction(propertyName);
  193.         }
  194.  
  195.         /// <summary>
  196.         /// Gets the string name for the property
  197.         /// </summary>
  198.         protected string GetPropertyName<T>(Expression<Func<T>> expression)
  199.         {
  200.             if (expression.NodeType != ExpressionType.Lambda)
  201.             {
  202.                 throw new ArgumentException("Value must be a lamda expression", "expression");
  203.             }
  204.  
  205.             if (!(expression.Body is MemberExpression))
  206.             {
  207.                 throw new ArgumentException("The body of the expression must be a memberref", "expression");
  208.             }
  209.  
  210.             MemberExpression memberExpression = (MemberExpression)expression.Body;
  211.             return memberExpression.Member.Name;
  212.         }
  213.     }
  214.  
  215. }
Advertisement
Add Comment
Please, Sign In to add comment