PointersPage.xaml.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using Avalonia.Controls;
  3. using Avalonia.Input;
  4. using Avalonia.Markup.Xaml;
  5. namespace ControlCatalog.Pages;
  6. public class PointersPage : UserControl
  7. {
  8. public PointersPage()
  9. {
  10. this.InitializeComponent();
  11. var border1 = this.Get<Border>("BorderCapture1");
  12. var border2 = this.Get<Border>("BorderCapture2");
  13. border1.PointerPressed += Border_PointerPressed;
  14. border1.PointerReleased += Border_PointerReleased;
  15. border1.PointerCaptureLost += Border_PointerCaptureLost;
  16. border1.PointerMoved += Border_PointerUpdated;
  17. border1.PointerEntered += Border_PointerUpdated;
  18. border1.PointerExited += Border_PointerUpdated;
  19. border2.PointerPressed += Border_PointerPressed;
  20. border2.PointerReleased += Border_PointerReleased;
  21. border2.PointerCaptureLost += Border_PointerCaptureLost;
  22. border2.PointerMoved += Border_PointerUpdated;
  23. border2.PointerEntered += Border_PointerUpdated;
  24. border2.PointerExited += Border_PointerUpdated;
  25. }
  26. private void Border_PointerUpdated(object? sender, PointerEventArgs e)
  27. {
  28. if (sender is Border border && border.Child is TextBlock textBlock)
  29. {
  30. var position = e.GetPosition(border);
  31. textBlock.Text = @$"Type: {e.Pointer.Type}
  32. Captured: {e.Pointer.Captured == sender}
  33. PointerId: {e.Pointer.Id}
  34. Position: {(int)position.X} {(int)position.Y}";
  35. e.Handled = true;
  36. }
  37. }
  38. private void Border_PointerCaptureLost(object? sender, PointerCaptureLostEventArgs e)
  39. {
  40. if (sender is Border border && border.Child is TextBlock textBlock)
  41. {
  42. textBlock.Text = @$"Type: {e.Pointer.Type}
  43. Captured: {e.Pointer.Captured == sender}
  44. PointerId: {e.Pointer.Id}
  45. Position: ??? ???";
  46. e.Handled = true;
  47. }
  48. }
  49. private void Border_PointerReleased(object? sender, PointerReleasedEventArgs e)
  50. {
  51. if (e.Pointer.Captured == sender)
  52. {
  53. e.Pointer.Capture(null);
  54. e.Handled = true;
  55. }
  56. else
  57. {
  58. throw new InvalidOperationException("How?");
  59. }
  60. }
  61. private void Border_PointerPressed(object? sender, PointerPressedEventArgs e)
  62. {
  63. e.Pointer.Capture(sender as Border);
  64. e.Handled = true;
  65. }
  66. private void InitializeComponent()
  67. {
  68. AvaloniaXamlLoader.Load(this);
  69. }
  70. }