IAsyncRelayCommandExtensions.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637
  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. using System;
  5. using System.Windows.Input;
  6. using CommunityToolkit.Mvvm.Input.Internals;
  7. namespace CommunityToolkit.Mvvm.Input;
  8. /// <summary>
  9. /// Extensions for the <see cref="IAsyncRelayCommand"/> type.
  10. /// </summary>
  11. public static class IAsyncRelayCommandExtensions
  12. {
  13. /// <summary>
  14. /// Creates an <see cref="ICommand"/> instance that can be used to cancel execution on the input command.
  15. /// The returned command will also notify when it can be executed based on the state of the wrapped command.
  16. /// </summary>
  17. /// <param name="command">The input <see cref="IAsyncRelayCommand"/> instance to create a cancellation command for.</param>
  18. /// <returns>An <see cref="ICommand"/> instance that can be used to monitor and signal cancellation for <paramref name="command"/>.</returns>
  19. /// <remarks>The returned instance is not guaranteed to be unique across multiple invocations with the same arguments.</remarks>
  20. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="command"/> is <see langword="null"/>.</exception>
  21. public static ICommand CreateCancelCommand(this IAsyncRelayCommand command)
  22. {
  23. ArgumentNullException.ThrowIfNull(command);
  24. // If the command is known not to ever allow cancellation, just reuse the same instance
  25. if (command is ICancellationAwareCommand { IsCancellationSupported: false })
  26. {
  27. return DisabledCommand.Instance;
  28. }
  29. // Create a new cancel command wrapping the input one
  30. return new CancelCommand(command);
  31. }
  32. }