ShowPointerPositionBehavior.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using Avalonia.Controls;
  2. using Avalonia.Input;
  3. using Avalonia.Xaml.Interactivity;
  4. namespace Avalonia.Xaml.Interactions.Custom;
  5. /// <summary>
  6. /// A behavior that displays cursor position on <see cref="InputElement.PointerMoved"/> event for the <see cref="StyledElementBehavior{T}.AssociatedObject"/> using <see cref="TextBlock.Text"/> property.
  7. /// </summary>
  8. public class ShowPointerPositionBehavior : StyledElementBehavior<Control>
  9. {
  10. /// <summary>
  11. /// Identifies the <seealso cref="TargetTextBlockProperty"/> avalonia property.
  12. /// </summary>
  13. public static readonly StyledProperty<TextBlock?> TargetTextBlockProperty =
  14. AvaloniaProperty.Register<ShowPointerPositionBehavior, TextBlock?>(nameof(TargetTextBlock));
  15. /// <summary>
  16. /// Gets or sets the target TextBlock object in which this behavior displays cursor position on PointerMoved event.
  17. /// </summary>
  18. [ResolveByName]
  19. public TextBlock? TargetTextBlock
  20. {
  21. get => GetValue(TargetTextBlockProperty);
  22. set => SetValue(TargetTextBlockProperty, value);
  23. }
  24. /// <inheritdoc />
  25. protected override void OnAttachedToVisualTree()
  26. {
  27. if (AssociatedObject is not null)
  28. {
  29. AssociatedObject.PointerMoved += AssociatedObject_PointerMoved;
  30. }
  31. }
  32. /// <inheritdoc />
  33. protected override void OnDetachedFromVisualTree()
  34. {
  35. if (AssociatedObject is not null)
  36. {
  37. AssociatedObject.PointerMoved -= AssociatedObject_PointerMoved;
  38. }
  39. }
  40. private void AssociatedObject_PointerMoved(object? sender, PointerEventArgs e)
  41. {
  42. if (TargetTextBlock is not null)
  43. {
  44. TargetTextBlock.Text = e.GetPosition(AssociatedObject).ToString();
  45. }
  46. }
  47. }