ToolTipService.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using Avalonia.Input;
  3. using Avalonia.Threading;
  4. namespace Avalonia.Controls
  5. {
  6. /// <summary>
  7. /// Handles <see cref="ToolTip"/> interaction with controls.
  8. /// </summary>
  9. internal sealed class ToolTipService
  10. {
  11. public static ToolTipService Instance { get; } = new ToolTipService();
  12. private DispatcherTimer _timer;
  13. private ToolTipService() { }
  14. /// <summary>
  15. /// called when the <see cref="ToolTip.TipProperty"/> property changes on a control.
  16. /// </summary>
  17. /// <param name="e">The event args.</param>
  18. internal void TipChanged(AvaloniaPropertyChangedEventArgs e)
  19. {
  20. var control = (Control)e.Sender;
  21. if (e.OldValue != null)
  22. {
  23. control.PointerEnter -= ControlPointerEnter;
  24. control.PointerLeave -= ControlPointerLeave;
  25. }
  26. if (e.NewValue != null)
  27. {
  28. control.PointerEnter += ControlPointerEnter;
  29. control.PointerLeave += ControlPointerLeave;
  30. }
  31. }
  32. /// <summary>
  33. /// Called when the pointer enters a control with an attached tooltip.
  34. /// </summary>
  35. /// <param name="sender">The event sender.</param>
  36. /// <param name="e">The event args.</param>
  37. private void ControlPointerEnter(object sender, PointerEventArgs e)
  38. {
  39. StopTimer();
  40. var control = (Control)sender;
  41. var showDelay = ToolTip.GetShowDelay(control);
  42. if (showDelay == 0)
  43. {
  44. Open(control);
  45. }
  46. else
  47. {
  48. StartShowTimer(showDelay, control);
  49. }
  50. }
  51. /// <summary>
  52. /// Called when the pointer leaves a control with an attached tooltip.
  53. /// </summary>
  54. /// <param name="sender">The event sender.</param>
  55. /// <param name="e">The event args.</param>
  56. private void ControlPointerLeave(object sender, PointerEventArgs e)
  57. {
  58. var control = (Control)sender;
  59. Close(control);
  60. }
  61. private void StartShowTimer(int showDelay, Control control)
  62. {
  63. _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(showDelay) };
  64. _timer.Tick += (o, e) => Open(control);
  65. _timer.Start();
  66. }
  67. private void Open(Control control)
  68. {
  69. StopTimer();
  70. ToolTip.SetIsOpen(control, true);
  71. }
  72. private void Close(Control control)
  73. {
  74. StopTimer();
  75. ToolTip.SetIsOpen(control, false);
  76. }
  77. private void StopTimer()
  78. {
  79. _timer?.Stop();
  80. _timer = null;
  81. }
  82. }
  83. }