ViewModelBase.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.ComponentModel;
  3. using System.Diagnostics;
  4. using System.Windows.Threading;
  5. using System.Windows;
  6. namespace WindowsPhone.Recipes.Push.Server.ViewModels
  7. {
  8. /// <summary>
  9. /// Base class for all ViewModel classes in the application.
  10. /// It provides support for property change notifications
  11. /// and has a DisplayName property. This class is abstract.
  12. /// </summary>
  13. public abstract class ViewModelBase : INotifyPropertyChanged
  14. {
  15. #region Properties
  16. public Dispatcher Dispatcher
  17. {
  18. get { return Application.Current.Dispatcher; }
  19. }
  20. #endregion
  21. #region Constructor
  22. protected ViewModelBase()
  23. {
  24. }
  25. #endregion // Constructor
  26. #region Debugging
  27. /// <summary>
  28. /// Warns the developer if this object does not have
  29. /// a public property with the specified name. This
  30. /// method does not exist in a Release build.
  31. /// </summary>
  32. [Conditional("DEBUG")]
  33. [DebuggerStepThrough]
  34. public void VerifyPropertyName(string propertyName)
  35. {
  36. // Verify that the property name matches a real,
  37. // public, instance property on this object.
  38. if (TypeDescriptor.GetProperties(this)[propertyName] == null)
  39. {
  40. string msg = "Invalid property name: " + propertyName;
  41. if (this.ThrowOnInvalidPropertyName)
  42. throw new Exception(msg);
  43. else
  44. Debug.Fail(msg);
  45. }
  46. }
  47. /// <summary>
  48. /// Returns whether an exception is thrown, or if a Debug.Fail() is used
  49. /// when an invalid property name is passed to the VerifyPropertyName method.
  50. /// The default value is false, but subclasses used by unit tests might
  51. /// override this property's getter to return true.
  52. /// </summary>
  53. protected virtual bool ThrowOnInvalidPropertyName { get; private set; }
  54. #endregion // Debugging Aides
  55. #region INotifyPropertyChanged Members
  56. /// <summary>
  57. /// Raised when a property on this object has a new value.
  58. /// </summary>
  59. public event PropertyChangedEventHandler PropertyChanged;
  60. /// <summary>
  61. /// Raises this object's PropertyChanged event.
  62. /// </summary>
  63. /// <param name="propertyName">The property that has a new value.</param>
  64. protected void NotifyPropertyChanged(string propertyName)
  65. {
  66. this.VerifyPropertyName(propertyName);
  67. PropertyChangedEventHandler handler = this.PropertyChanged;
  68. if (handler != null)
  69. {
  70. var e = new PropertyChangedEventArgs(propertyName);
  71. handler(this, e);
  72. }
  73. }
  74. #endregion // INotifyPropertyChanged Members
  75. }
  76. }