using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
///
/// A behavior that displays cursor position on event for the using property.
///
public class ShowPointerPositionBehavior : StyledElementBehavior
{
///
/// Identifies the avalonia property.
///
public static readonly StyledProperty TargetTextBlockProperty =
AvaloniaProperty.Register(nameof(TargetTextBlock));
///
/// Gets or sets the target TextBlock object in which this behavior displays cursor position on PointerMoved event.
///
[ResolveByName]
public TextBlock? TargetTextBlock
{
get => GetValue(TargetTextBlockProperty);
set => SetValue(TargetTextBlockProperty, value);
}
///
protected override void OnAttachedToVisualTree()
{
if (AssociatedObject is not null)
{
AssociatedObject.PointerMoved += AssociatedObject_PointerMoved;
}
}
///
protected override void OnDetachedFromVisualTree()
{
if (AssociatedObject is not null)
{
AssociatedObject.PointerMoved -= AssociatedObject_PointerMoved;
}
}
private void AssociatedObject_PointerMoved(object? sender, PointerEventArgs e)
{
if (TargetTextBlock is not null)
{
TargetTextBlock.Text = e.GetPosition(AssociatedObject).ToString();
}
}
}