SelectListBoxItemOnPointerMovedBehavior.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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. /// Sets <see cref="ListBoxItem.IsSelected"/> property to true of the associated <see cref="ListBoxItem"/> control on <see cref="InputElement.PointerMoved"/> event.
  8. /// </summary>
  9. public class SelectListBoxItemOnPointerMovedBehavior : 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. if (AssociatedObject is {Parent: ListBoxItem item})
  30. {
  31. item.SetCurrentValue(ListBoxItem.IsSelectedProperty, true);
  32. Dispatcher.UIThread.Post(() => item.Focus());
  33. }
  34. }
  35. }