ShowOnKeyDownBehavior.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Reactive.Disposables;
  2. using Avalonia.Input;
  3. using Avalonia.Interactivity;
  4. namespace Avalonia.Xaml.Interactions.Custom;
  5. /// <summary>
  6. /// A behavior that allows to show control on key down event.
  7. /// </summary>
  8. public class ShowOnKeyDownBehavior : ShowBehaviorBase
  9. {
  10. /// <summary>
  11. /// Identifies the <seealso cref="Key"/> avalonia property.
  12. /// </summary>
  13. public static readonly StyledProperty<Key?> KeyProperty =
  14. AvaloniaProperty.Register<ShowOnKeyDownBehavior, Key?>(nameof(Key));
  15. /// <summary>
  16. ///
  17. /// </summary>
  18. public static readonly StyledProperty<KeyGesture?> GestureProperty =
  19. AvaloniaProperty.Register<ShowOnKeyDownBehavior, KeyGesture?>(nameof(Gesture));
  20. /// <summary>
  21. /// Gets or sets the key. This is a avalonia property.
  22. /// </summary>
  23. public Key? Key
  24. {
  25. get => GetValue(KeyProperty);
  26. set => SetValue(KeyProperty, value);
  27. }
  28. /// <summary>
  29. ///
  30. /// </summary>
  31. public KeyGesture? Gesture
  32. {
  33. get => GetValue(GestureProperty);
  34. set => SetValue(GestureProperty, value);
  35. }
  36. /// <summary>
  37. ///
  38. /// </summary>
  39. /// <param name="disposable"></param>
  40. protected override void OnAttachedToVisualTree(CompositeDisposable disposable)
  41. {
  42. var dispose = AssociatedObject?
  43. .AddDisposableHandler(
  44. InputElement.KeyDownEvent,
  45. AssociatedObject_KeyDown,
  46. EventRoutingStrategy);
  47. if (dispose is not null)
  48. {
  49. disposable.Add(dispose);
  50. }
  51. }
  52. private void AssociatedObject_KeyDown(object? sender, KeyEventArgs e)
  53. {
  54. var haveKey = Key is not null && e.Key == Key;
  55. var haveGesture = Gesture is not null && Gesture.Matches(e);
  56. if (!haveKey && !haveGesture)
  57. {
  58. return;
  59. }
  60. Show();
  61. }
  62. }