CancelCommand.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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.ComponentModel;
  6. using System.Windows.Input;
  7. namespace CommunityToolkit.Mvvm.Input.Internals;
  8. /// <summary>
  9. /// A <see cref="ICommand"/> implementation wrapping <see cref="IAsyncRelayCommand"/> to support cancellation.
  10. /// </summary>
  11. internal sealed partial class CancelCommand : ICommand
  12. {
  13. /// <summary>
  14. /// The wrapped <see cref="IAsyncRelayCommand"/> instance.
  15. /// </summary>
  16. private readonly IAsyncRelayCommand command;
  17. /// <summary>
  18. /// Creates a new <see cref="CancelCommand"/> instance.
  19. /// </summary>
  20. /// <param name="command">The <see cref="IAsyncRelayCommand"/> instance to wrap.</param>
  21. public CancelCommand(IAsyncRelayCommand command)
  22. {
  23. this.command = command;
  24. this.command.PropertyChanged += OnPropertyChanged;
  25. }
  26. /// <inheritdoc/>
  27. public event EventHandler? CanExecuteChanged;
  28. /// <inheritdoc/>
  29. public bool CanExecute(object? parameter)
  30. {
  31. return this.command.CanBeCanceled;
  32. }
  33. /// <inheritdoc/>
  34. public void Execute(object? parameter)
  35. {
  36. this.command.Cancel();
  37. }
  38. /// <inheritdoc cref="PropertyChangedEventHandler"/>
  39. private void OnPropertyChanged(object? sender, PropertyChangedEventArgs e)
  40. {
  41. if (e.PropertyName is null or nameof(IAsyncRelayCommand.CanBeCanceled))
  42. {
  43. CanExecuteChanged?.Invoke(this, EventArgs.Empty);
  44. }
  45. }
  46. }