FocusOnPointerMovedBehavior.cs 942 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="IBehavior.AssociatedObject"/> on <see cref="InputElement.PointerMoved"/> event.
  8. /// </summary>
  9. public class FocusOnPointerMovedBehavior : StyledElementBehavior<Control>
  10. {
  11. /// <inheritdoc />
  12. protected override void OnAttachedToVisualTree()
  13. {
  14. if (AssociatedObject is not null)
  15. {
  16. AssociatedObject.PointerMoved += PointerMoved;
  17. }
  18. }
  19. /// <inheritdoc />
  20. protected override void OnDetachedFromVisualTree()
  21. {
  22. if (AssociatedObject is not null)
  23. {
  24. AssociatedObject.PointerMoved -= PointerMoved;
  25. }
  26. }
  27. private void PointerMoved(object? sender, PointerEventArgs args)
  28. {
  29. Dispatcher.UIThread.Post(() => AssociatedObject?.Focus());
  30. }
  31. }