DelegateCommandBase.cs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Linq.Expressions;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Windows.Input;
  8. namespace HandyControl.Interactivity.Commands
  9. {
  10. /// <summary>
  11. /// An <see cref="ICommand"/> whose delegates can be attached for <see cref="Execute"/> and <see cref="CanExecute"/>.
  12. /// </summary>
  13. public abstract class DelegateCommandBase : BindableBase, ICommand, IActiveAware
  14. {
  15. private bool _isActive;
  16. private SynchronizationContext? _synchronizationContext;
  17. private readonly HashSet<string> _observedPropertiesExpressions = new();
  18. /// <summary>
  19. /// Provides an Exception Handler to register callbacks or handle encountered exceptions within
  20. /// </summary>
  21. protected readonly MulticastExceptionHandler ExceptionHandler = new();
  22. /// <summary>
  23. /// Creates a new instance of a <see cref="DelegateCommandBase"/>, specifying both the execute action and the can execute function.
  24. /// </summary>
  25. protected DelegateCommandBase()
  26. {
  27. _synchronizationContext = SynchronizationContext.Current;
  28. }
  29. /// <summary>
  30. /// Occurs when changes occur that affect whether or not the command should execute.
  31. /// </summary>
  32. public virtual event EventHandler? CanExecuteChanged;
  33. /// <summary>
  34. /// Raises <see cref="ICommand.CanExecuteChanged"/> so every
  35. /// command invoker can re-query <see cref="ICommand.CanExecute"/>.
  36. /// </summary>
  37. protected virtual void OnCanExecuteChanged()
  38. {
  39. var handler = CanExecuteChanged;
  40. if (handler != null)
  41. {
  42. if (_synchronizationContext != null && _synchronizationContext != SynchronizationContext.Current)
  43. _synchronizationContext.Post((o) => handler.Invoke(this, EventArgs.Empty), null);
  44. else
  45. handler.Invoke(this, EventArgs.Empty);
  46. }
  47. }
  48. /// <summary>
  49. /// Raises <see cref="CanExecuteChanged"/> so every command invoker
  50. /// can re-query to check if the command can execute.
  51. /// </summary>
  52. /// <remarks>Note that this will trigger the execution of <see cref="CanExecuteChanged"/> once for each invoker.</remarks>
  53. [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
  54. public void RaiseCanExecuteChanged()
  55. {
  56. OnCanExecuteChanged();
  57. }
  58. void ICommand.Execute(object? parameter)
  59. {
  60. Execute(parameter);
  61. }
  62. bool ICommand.CanExecute(object? parameter)
  63. {
  64. return CanExecute(parameter);
  65. }
  66. /// <summary>
  67. /// Handle the internal invocation of <see cref="ICommand.Execute(object)"/>
  68. /// </summary>
  69. /// <param name="parameter">Command Parameter</param>
  70. protected abstract void Execute(object? parameter);
  71. /// <summary>
  72. /// Handle the internal invocation of <see cref="ICommand.CanExecute(object)"/>
  73. /// </summary>
  74. /// <param name="parameter"></param>
  75. /// <returns><see langword="true"/> if the Command Can Execute, otherwise <see langword="false" /></returns>
  76. protected abstract bool CanExecute(object? parameter);
  77. /// <summary>
  78. /// Observes a property that implements INotifyPropertyChanged, and automatically calls DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications.
  79. /// </summary>
  80. /// <typeparam name="T">The object type containing the property specified in the expression.</typeparam>
  81. /// <param name="propertyExpression">The property expression. Example: ObservesProperty(() => PropertyName).</param>
  82. protected internal void ObservesPropertyInternal<T>(Expression<Func<T>> propertyExpression)
  83. {
  84. if (_observedPropertiesExpressions.Contains(propertyExpression.ToString()))
  85. {
  86. throw new ArgumentException($"{propertyExpression} is already being observed.",
  87. nameof(propertyExpression));
  88. }
  89. else
  90. {
  91. _observedPropertiesExpressions.Add(propertyExpression.ToString());
  92. PropertyObserver.Observes(propertyExpression, RaiseCanExecuteChanged);
  93. }
  94. }
  95. #region IsActive
  96. /// <summary>
  97. /// Gets or sets a value indicating whether the object is active.
  98. /// </summary>
  99. /// <value><see langword="true" /> if the object is active; otherwise <see langword="false" />.</value>
  100. public bool IsActive
  101. {
  102. get => _isActive;
  103. set => SetProperty(ref _isActive, value, OnIsActiveChanged);
  104. }
  105. /// <summary>
  106. /// Fired if the <see cref="IsActive"/> property changes.
  107. /// </summary>
  108. public virtual event EventHandler? IsActiveChanged;
  109. /// <summary>
  110. /// This raises the <see cref="IsActiveChanged"/> event.
  111. /// </summary>
  112. protected virtual void OnIsActiveChanged()
  113. {
  114. IsActiveChanged?.Invoke(this, EventArgs.Empty);
  115. }
  116. #endregion
  117. }
  118. }