HideOnLostFocusBehavior.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 lost focus event.
  8. /// </summary>
  9. public class HideOnLostFocusBehavior : 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<HideOnLostFocusBehavior, Control?>(nameof(TargetControl));
  16. /// <summary>
  17. /// Gets or sets the target control. This is a avalonia property.
  18. /// </summary>
  19. [ResolveByName]
  20. public Control? TargetControl
  21. {
  22. get => GetValue(TargetControlProperty);
  23. set => SetValue(TargetControlProperty, value);
  24. }
  25. /// <inheritdoc />
  26. protected override void OnAttachedToVisualTree()
  27. {
  28. AssociatedObject?.AddHandler(InputElement.LostFocusEvent, AssociatedObject_LostFocus,
  29. RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
  30. }
  31. /// <inheritdoc />
  32. protected override void OnDetachedFromVisualTree()
  33. {
  34. AssociatedObject?.RemoveHandler(InputElement.LostFocusEvent, AssociatedObject_LostFocus);
  35. }
  36. private void AssociatedObject_LostFocus(object? sender, RoutedEventArgs e)
  37. {
  38. if (TargetControl is not null)
  39. {
  40. TargetControl.IsVisible = false;
  41. }
  42. }
  43. }