HideOnKeyPressedBehavior.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 allows to hide control on key down event.
  8. /// </summary>
  9. public class HideOnKeyPressedBehavior : StyledElementBehavior<Control>
  10. {
  11. /// <summary>
  12. /// Identifies the <seealso cref="TargetControl"/> avalonia property.
  13. /// </summary>
  14. public static readonly StyledProperty<Control?> TargetControlProperty =
  15. AvaloniaProperty.Register<HideOnKeyPressedBehavior, Control?>(nameof(TargetControl));
  16. /// <summary>
  17. /// Identifies the <seealso cref="Key"/> avalonia property.
  18. /// </summary>
  19. public static readonly StyledProperty<Key> KeyProperty =
  20. AvaloniaProperty.Register<HideOnKeyPressedBehavior, Key>(nameof(Key), Key.Escape);
  21. /// <summary>
  22. /// Gets or sets the target control. This is a avalonia property.
  23. /// </summary>
  24. [ResolveByName]
  25. public Control? TargetControl
  26. {
  27. get => GetValue(TargetControlProperty);
  28. set => SetValue(TargetControlProperty, value);
  29. }
  30. /// <summary>
  31. /// Gets or sets the key. This is a avalonia property.
  32. /// </summary>
  33. public Key Key
  34. {
  35. get => GetValue(KeyProperty);
  36. set => SetValue(KeyProperty, value);
  37. }
  38. /// <inheritdoc />
  39. protected override void OnAttachedToVisualTree()
  40. {
  41. AssociatedObject?.AddHandler(InputElement.KeyDownEvent, AssociatedObject_KeyDown,
  42. RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
  43. }
  44. /// <inheritdoc />
  45. protected override void OnDetachedFromVisualTree()
  46. {
  47. AssociatedObject?.RemoveHandler(InputElement.KeyDownEvent, AssociatedObject_KeyDown);
  48. }
  49. private void AssociatedObject_KeyDown(object? sender, KeyEventArgs e)
  50. {
  51. if (e.Key == Key && TargetControl is not null)
  52. {
  53. TargetControl.IsVisible = false;
  54. }
  55. }
  56. }