ButtonClickEventTriggerBehavior.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using Avalonia.Controls;
  2. using Avalonia.Input;
  3. using Avalonia.Interactivity;
  4. using Avalonia.Xaml.Interactivity;
  5. namespace Avalonia.Xaml.Interactions.Custom;
  6. /// <summary>
  7. /// A behavior that listens for a <see cref="Button.ClickEvent"/> event on its source and executes its actions when that event is fired.
  8. /// </summary>
  9. public class ButtonClickEventTriggerBehavior : StyledElementTrigger<Button>
  10. {
  11. private KeyModifiers _savedKeyModifiers = KeyModifiers.None;
  12. /// <summary>
  13. /// Identifies the <seealso cref="KeyModifiers"/> avalonia property.
  14. /// </summary>
  15. public static readonly StyledProperty<KeyModifiers> KeyModifiersProperty =
  16. AvaloniaProperty.Register<ButtonClickEventTriggerBehavior, KeyModifiers>(nameof(KeyModifiers));
  17. /// <summary>
  18. /// Gets or sets the required key modifiers to execute <see cref="Button.ClickEvent"/> event handler. This is a avalonia property.
  19. /// </summary>
  20. public KeyModifiers KeyModifiers
  21. {
  22. get => GetValue(KeyModifiersProperty);
  23. set => SetValue(KeyModifiersProperty, value);
  24. }
  25. /// <inheritdoc />
  26. protected override void OnAttachedToVisualTree()
  27. {
  28. if (AssociatedObject is not null)
  29. {
  30. AssociatedObject.Click += AssociatedObject_OnClick;
  31. AssociatedObject.AddHandler(InputElement.KeyDownEvent, Button_OnKeyDown, RoutingStrategies.Tunnel);
  32. AssociatedObject.AddHandler(InputElement.KeyUpEvent, Button_OnKeyUp, RoutingStrategies.Tunnel);
  33. }
  34. }
  35. /// <inheritdoc />
  36. protected override void OnDetachedFromVisualTree()
  37. {
  38. if (AssociatedObject is not null)
  39. {
  40. AssociatedObject.Click -= AssociatedObject_OnClick;
  41. AssociatedObject.RemoveHandler(InputElement.KeyDownEvent, Button_OnKeyDown);
  42. AssociatedObject.RemoveHandler(InputElement.KeyUpEvent, Button_OnKeyUp);
  43. }
  44. }
  45. private void AssociatedObject_OnClick(object? sender, RoutedEventArgs e)
  46. {
  47. if (!IsEnabled)
  48. {
  49. return;
  50. }
  51. if (AssociatedObject is not null && KeyModifiers == _savedKeyModifiers)
  52. {
  53. Interaction.ExecuteActions(AssociatedObject, Actions, e);
  54. }
  55. }
  56. private void Button_OnKeyDown(object? sender, KeyEventArgs e)
  57. {
  58. _savedKeyModifiers = e.KeyModifiers;
  59. }
  60. private void Button_OnKeyUp(object? sender, KeyEventArgs e)
  61. {
  62. _savedKeyModifiers = KeyModifiers.None;
  63. }
  64. }