FocusOnPointerPressedBehavior.cs 975 B

1234567891011121314151617181920212223242526272829303132333435
  1. using Avalonia.Controls;
  2. using Avalonia.Input;
  3. using Avalonia.Threading;
  4. using Avalonia.Xaml.Interactivity;
  5. namespace Avalonia.Xaml.Interactions.Custom;
  6. /// <summary>
  7. /// Focuses the <see cref="StyledElementBehavior{T}.AssociatedObject"/> on <see cref="InputElement.PointerPressed"/> event.
  8. /// </summary>
  9. public class FocusOnPointerPressedBehavior : StyledElementBehavior<Control>
  10. {
  11. /// <inheritdoc />
  12. protected override void OnAttachedToVisualTree()
  13. {
  14. if (AssociatedObject is not null)
  15. {
  16. AssociatedObject.PointerPressed += PointerPressed;
  17. }
  18. }
  19. /// <inheritdoc />
  20. protected override void OnDetachedFromVisualTree()
  21. {
  22. if (AssociatedObject is not null)
  23. {
  24. AssociatedObject.PointerPressed -= PointerPressed;
  25. }
  26. }
  27. private void PointerPressed(object? sender, PointerPressedEventArgs e)
  28. {
  29. Dispatcher.UIThread.Post(() => AssociatedObject?.Focus());
  30. }
  31. }