RelayCommand{T}.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. // This file is inspired from the MvvmLight library (lbugnion/MvvmLight),
  5. // more info in ThirdPartyNotices.txt in the root of the project.
  6. using System;
  7. using System.Diagnostics.CodeAnalysis;
  8. using System.Runtime.CompilerServices;
  9. namespace CommunityToolkit.Mvvm.Input;
  10. /// <summary>
  11. /// A generic command whose sole purpose is to relay its functionality to other
  12. /// objects by invoking delegates. The default return value for the CanExecute
  13. /// method is <see langword="true"/>. This class allows you to accept command parameters
  14. /// in the <see cref="Execute(T)"/> and <see cref="CanExecute(T)"/> callback methods.
  15. /// </summary>
  16. /// <typeparam name="T">The type of parameter being passed as input to the callbacks.</typeparam>
  17. public sealed partial class RelayCommand<T> : IRelayCommand<T>
  18. {
  19. /// <summary>
  20. /// The <see cref="Action"/> to invoke when <see cref="Execute(T)"/> is used.
  21. /// </summary>
  22. private readonly Action<T?> execute;
  23. private readonly Action<object?, T?> execute1;
  24. /// <summary>
  25. /// The optional action to invoke when <see cref="CanExecute(T)"/> is used.
  26. /// </summary>
  27. private readonly Predicate<T?>? canExecute;
  28. /// <inheritdoc/>
  29. public event EventHandler? CanExecuteChanged;
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="RelayCommand{T}"/> class that can always execute.
  32. /// </summary>
  33. /// <param name="execute">The execution logic.</param>
  34. /// <remarks>
  35. /// Due to the fact that the <see cref="System.Windows.Input.ICommand"/> interface exposes methods that accept a
  36. /// nullable <see cref="object"/> parameter, it is recommended that if <typeparamref name="T"/> is a reference type,
  37. /// you should always declare it as nullable, and to always perform checks within <paramref name="execute"/>.
  38. /// </remarks>
  39. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="execute"/> is <see langword="null"/>.</exception>
  40. public RelayCommand(Action<T?> execute)
  41. {
  42. ArgumentNullException.ThrowIfNull(execute);
  43. this.execute = execute;
  44. }
  45. public RelayCommand(Action<object?, T?> execute)
  46. {
  47. ArgumentNullException.ThrowIfNull(execute);
  48. this.execute1 = execute;
  49. }
  50. /// <summary>
  51. /// Initializes a new instance of the <see cref="RelayCommand{T}"/> class.
  52. /// </summary>
  53. /// <param name="execute">The execution logic.</param>
  54. /// <param name="canExecute">The execution status logic.</param>
  55. /// <remarks>See notes in <see cref="RelayCommand{T}(Action{T})"/>.</remarks>
  56. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="execute"/> or <paramref name="canExecute"/> are <see langword="null"/>.</exception>
  57. public RelayCommand(Action<T?> execute, Predicate<T?> canExecute)
  58. {
  59. ArgumentNullException.ThrowIfNull(execute);
  60. ArgumentNullException.ThrowIfNull(canExecute);
  61. this.execute = execute;
  62. this.canExecute = canExecute;
  63. }
  64. public RelayCommand(Action<object?,T?> execute, Predicate<T?> canExecute)
  65. {
  66. ArgumentNullException.ThrowIfNull(execute);
  67. ArgumentNullException.ThrowIfNull(canExecute);
  68. this.execute1 = execute;
  69. this.canExecute = canExecute;
  70. }
  71. /// <inheritdoc/>
  72. public void NotifyCanExecuteChanged()
  73. {
  74. CanExecuteChanged?.Invoke(this, EventArgs.Empty);
  75. }
  76. /// <inheritdoc/>
  77. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  78. public bool CanExecute(T? parameter)
  79. {
  80. return this.canExecute?.Invoke(parameter) != false;
  81. }
  82. /// <inheritdoc/>
  83. public bool CanExecute(object? parameter)
  84. {
  85. // Special case a null value for a value type argument type.
  86. // This ensures that no exceptions are thrown during initialization.
  87. if (parameter is null && default(T) is not null)
  88. {
  89. return false;
  90. }
  91. if (!TryGetCommandArgument(parameter, out T? result))
  92. {
  93. ThrowArgumentExceptionForInvalidCommandArgument(parameter);
  94. }
  95. return CanExecute(result);
  96. }
  97. /// <inheritdoc/>
  98. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  99. public void Execute(object? sender,T? parameter)
  100. {
  101. if (execute1 == null) execute(parameter);
  102. else this.execute1(sender, parameter);
  103. }
  104. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  105. public void Execute(T? parameter)
  106. {
  107. Execute(null, parameter);
  108. }
  109. public void Execute(object? sender, object? parameter)
  110. {
  111. if (!TryGetCommandArgument(parameter, out T? result))
  112. {
  113. ThrowArgumentExceptionForInvalidCommandArgument(parameter);
  114. }
  115. Execute(sender,result);
  116. }
  117. public void Execute(object? parameter)
  118. {
  119. if (!TryGetCommandArgument(parameter, out T? result))
  120. {
  121. ThrowArgumentExceptionForInvalidCommandArgument(parameter);
  122. }
  123. Execute(null, result);
  124. }
  125. /// <summary>
  126. /// Tries to get a command argument of compatible type <typeparamref name="T"/> from an input <see cref="object"/>.
  127. /// </summary>
  128. /// <param name="parameter">The input parameter.</param>
  129. /// <param name="result">The resulting <typeparamref name="T"/> value, if any.</param>
  130. /// <returns>Whether or not a compatible command argument could be retrieved.</returns>
  131. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  132. internal static bool TryGetCommandArgument(object? parameter, out T? result)
  133. {
  134. // If the argument is null and the default value of T is also null, then the
  135. // argument is valid. T might be a reference type or a nullable value type.
  136. if (parameter is null && default(T) is null)
  137. {
  138. result = default;
  139. return true;
  140. }
  141. // Check if the argument is a T value, so either an instance of a type or a derived
  142. // type of T is a reference type, an interface implementation if T is an interface,
  143. // or a boxed value type in case T was a value type.
  144. if (parameter is T argument)
  145. {
  146. result = argument;
  147. return true;
  148. }
  149. result = default;
  150. return false;
  151. }
  152. /// <summary>
  153. /// Throws an <see cref="ArgumentException"/> if an invalid command argument is used.
  154. /// </summary>
  155. /// <param name="parameter">The input parameter.</param>
  156. /// <exception cref="ArgumentException">Thrown with an error message to give info on the invalid parameter.</exception>
  157. [DoesNotReturn]
  158. internal static void ThrowArgumentExceptionForInvalidCommandArgument(object? parameter)
  159. {
  160. [MethodImpl(MethodImplOptions.NoInlining)]
  161. static Exception GetException(object? parameter)
  162. {
  163. if (parameter is null)
  164. {
  165. return new ArgumentException($"Parameter \"{nameof(parameter)}\" (object) must not be null, as the command type requires an argument of type {typeof(T)}.", nameof(parameter));
  166. }
  167. return new ArgumentException($"Parameter \"{nameof(parameter)}\" (object) cannot be of type {parameter.GetType()}, as the command type requires an argument of type {typeof(T)}.", nameof(parameter));
  168. }
  169. throw GetException(parameter);
  170. }
  171. }