ExecuteCommandOnKeyUpBehavior.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System.Reactive.Disposables;
  2. using Avalonia.Input;
  3. using Avalonia.Interactivity;
  4. namespace Avalonia.Xaml.Interactions.Custom;
  5. /// <summary>
  6. ///
  7. /// </summary>
  8. public class ExecuteCommandOnKeyUpBehavior : ExecuteCommandOnKeyBehaviorBase
  9. {
  10. /// <summary>
  11. ///
  12. /// </summary>
  13. /// <param name="disposable"></param>
  14. protected override void OnAttachedToVisualTree(CompositeDisposable disposable)
  15. {
  16. var control = SourceControl ?? AssociatedObject;
  17. var dispose = control?
  18. .AddDisposableHandler(
  19. InputElement.KeyUpEvent,
  20. OnKeyUp,
  21. EventRoutingStrategy);
  22. if (dispose is not null)
  23. {
  24. disposable.Add(dispose);
  25. }
  26. }
  27. private void OnKeyUp(object? sender, KeyEventArgs e)
  28. {
  29. var haveKey = Key is not null && e.Key == Key;
  30. var haveGesture = Gesture is not null && Gesture.Matches(e);
  31. if (!haveKey && !haveGesture)
  32. {
  33. return;
  34. }
  35. if (e.Handled)
  36. {
  37. return;
  38. }
  39. if (ExecuteCommand())
  40. {
  41. e.Handled = MarkAsHandled;
  42. }
  43. }
  44. }