ModernTooltip.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using System.Windows;
  2. using System.Windows.Controls;
  3. using System.Windows.Controls.Primitives;
  4. using System.Windows.Input;
  5. using System.Windows.Media;
  6. using System.Windows.Media.Animation;
  7. using System.Windows.Media.Effects;
  8. using System.Windows.Threading;
  9. namespace MeloongCore.Wpf;
  10. public static class ModernToolTipService {
  11. public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached(
  12. "IsEnabled", typeof(bool), typeof(ModernToolTipService), new PropertyMetadata(true));
  13. public static readonly DependencyProperty FollowMouseProperty = DependencyProperty.RegisterAttached(
  14. "FollowMouse", typeof(bool), typeof(ModernToolTipService), new PropertyMetadata(true));
  15. private static readonly TimeSpan animationTime = TimeSpan.FromMilliseconds(70);
  16. private static readonly int shadowRadius = 18;
  17. private static readonly float shadowOpacity = 0.15f;
  18. private static readonly Thickness contentMargin = new(12, 11, 12, 8.5);
  19. private static readonly Brush backgroundBrush = new SolidColorBrush(Colors.White);
  20. private static readonly Brush borderBrush = new SolidColorBrush(Color.FromRgb(0xD6, 0xD6, 0xD6));
  21. private static readonly Brush foregroundBrush = new SolidColorBrush(Color.FromRgb(0x52, 0x52, 0x52));
  22. private static readonly DispatcherTimer openTimer = new();
  23. private static bool initialized;
  24. private static int animationToken;
  25. private static Point lastMousePoint;
  26. private static Popup? popup;
  27. private static Border? popupCard;
  28. private static ScaleTransform? popupScale;
  29. private static FrameworkElement? currentOwner;
  30. private static ToolTip? borrowedToolTip;
  31. private static object? borrowedContent;
  32. static ModernToolTipService() {
  33. openTimer.Tick += (_, _) => {
  34. openTimer.Stop();
  35. if (currentOwner is not null) Show(currentOwner, lastMousePoint);
  36. };
  37. }
  38. /// <summary>
  39. /// 全局启用现代 Tooltip。启用后会接管所有 <see cref="FrameworkElement.ToolTip"/>。
  40. /// </summary>
  41. public static void Initialize() {
  42. if (initialized) return;
  43. initialized = true;
  44. EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.MouseEnterEvent, new MouseEventHandler(OnMouseEnter), true);
  45. EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.MouseMoveEvent, new MouseEventHandler(OnMouseMove), true);
  46. EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.MouseLeaveEvent, new MouseEventHandler(OnMouseLeave), true);
  47. EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.UnloadedEvent, new RoutedEventHandler(OnUnloaded), true);
  48. EventManager.RegisterClassHandler(typeof(FrameworkElement), ToolTipService.ToolTipOpeningEvent, new ToolTipEventHandler(OnNativeToolTipOpening), true);
  49. }
  50. public static void SetIsEnabled(DependencyObject element, bool value) => element.SetValue(IsEnabledProperty, value);
  51. public static bool GetIsEnabled(DependencyObject element) => (bool) element.GetValue(IsEnabledProperty);
  52. public static void SetFollowMouse(DependencyObject element, bool value) => element.SetValue(FollowMouseProperty, value);
  53. public static bool GetFollowMouse(DependencyObject element) => (bool) element.GetValue(FollowMouseProperty);
  54. private static void OnMouseEnter(object sender, MouseEventArgs e) {
  55. if (sender is not FrameworkElement owner || !GetIsEnabled(owner) || GetToolTipContent(owner) is null) return;
  56. if (ReferenceEquals(currentOwner, owner) && popup is { IsOpen: true }) return;
  57. if (!ReferenceEquals(currentOwner, owner)) HideImmediately();
  58. currentOwner = owner;
  59. lastMousePoint = e.GetPosition(owner);
  60. openTimer.Stop();
  61. var delay = Math.Max(0, ToolTipService.GetInitialShowDelay(owner));
  62. if (delay == 0) {
  63. Show(owner, lastMousePoint);
  64. } else {
  65. openTimer.Interval = TimeSpan.FromMilliseconds(delay);
  66. openTimer.Start();
  67. }
  68. }
  69. private static void OnMouseMove(object sender, MouseEventArgs e) {
  70. if (sender is not FrameworkElement owner || !ReferenceEquals(owner, currentOwner)) return;
  71. lastMousePoint = e.GetPosition(owner);
  72. if (GetFollowMouse(owner) && popup is { IsOpen: true }) UpdatePosition(owner, lastMousePoint);
  73. }
  74. private static void OnMouseLeave(object sender, MouseEventArgs e) {
  75. if (sender is FrameworkElement owner && ReferenceEquals(owner, currentOwner)) Close(true);
  76. }
  77. private static void OnUnloaded(object sender, RoutedEventArgs e) {
  78. if (sender is FrameworkElement owner && ReferenceEquals(owner, currentOwner)) Close(false);
  79. }
  80. private static void OnNativeToolTipOpening(object sender, ToolTipEventArgs e) {
  81. if (sender is FrameworkElement owner && GetIsEnabled(owner) && GetToolTipContent(owner) is not null) e.Handled = true;
  82. }
  83. private static object? GetToolTipContent(FrameworkElement owner) {
  84. var raw = owner.ToolTip;
  85. var content = raw is ToolTip toolTip ? toolTip.Content : raw;
  86. return content is string text && text.Length == 0 ? null : content;
  87. }
  88. private static void Show(FrameworkElement owner, Point point) {
  89. if (!ReferenceEquals(owner, currentOwner)) return;
  90. var raw = owner.ToolTip;
  91. var sourceToolTip = raw as ToolTip;
  92. var content = sourceToolTip?.Content ?? raw;
  93. if (content is null) return;
  94. if (content is string text && text.Length == 0) return;
  95. EnsurePopup();
  96. popup!.PlacementTarget = owner;
  97. popupCard!.DataContext = sourceToolTip?.DataContext ?? owner.DataContext;
  98. popupCard.FlowDirection = owner.FlowDirection;
  99. UpdatePosition(owner, point);
  100. popupCard.Child = null;
  101. RestoreBorrowedContent();
  102. if (sourceToolTip is not null && content is DependencyObject contentObject && ReferenceEquals(LogicalTreeHelper.GetParent(contentObject), sourceToolTip)) {
  103. borrowedToolTip = sourceToolTip;
  104. borrowedContent = content;
  105. sourceToolTip.Content = null;
  106. }
  107. popupCard.Child = content is string stringContent && sourceToolTip?.ContentTemplate is null && sourceToolTip?.ContentTemplateSelector is null
  108. ? new TextBlock {
  109. Text = stringContent,
  110. TextWrapping = TextWrapping.Wrap,
  111. Foreground = foregroundBrush,
  112. Margin = contentMargin,
  113. FontSize = 12.5,
  114. LineHeight = 17,
  115. MaxWidth = 676
  116. }
  117. : new ContentPresenter {
  118. Content = content,
  119. ContentTemplate = sourceToolTip?.ContentTemplate,
  120. ContentTemplateSelector = sourceToolTip?.ContentTemplateSelector,
  121. ContentStringFormat = sourceToolTip?.ContentStringFormat,
  122. Margin = contentMargin,
  123. MaxWidth = 676
  124. };
  125. animationToken++;
  126. popupCard.Opacity = 0;
  127. popupScale!.ScaleX = 0.97;
  128. popupScale.ScaleY = 0.97;
  129. popup.IsOpen = true;
  130. Animate(1, 1, null);
  131. }
  132. private static void Close(bool animated) {
  133. openTimer.Stop();
  134. currentOwner = null;
  135. if (popup is null || popupCard is null) return;
  136. if (!popup.IsOpen || !animated) {
  137. HideImmediately();
  138. return;
  139. }
  140. var token = ++animationToken;
  141. Animate(0, 0.97, (_, _) => {
  142. if (token != animationToken) return;
  143. HideImmediately();
  144. });
  145. }
  146. private static void HideImmediately() {
  147. animationToken++;
  148. if (popup is not null) popup.IsOpen = false;
  149. if (popupCard is not null) {
  150. popupCard.BeginAnimation(UIElement.OpacityProperty, null);
  151. popupCard.Child = null;
  152. }
  153. if (popupScale is not null) {
  154. popupScale.BeginAnimation(ScaleTransform.ScaleXProperty, null);
  155. popupScale.BeginAnimation(ScaleTransform.ScaleYProperty, null);
  156. }
  157. RestoreBorrowedContent();
  158. }
  159. private static void RestoreBorrowedContent() {
  160. if (borrowedToolTip is null) return;
  161. borrowedToolTip.Content = borrowedContent;
  162. borrowedToolTip = null;
  163. borrowedContent = null;
  164. }
  165. private static void EnsurePopup() {
  166. if (popup is not null) return;
  167. popupScale = new ScaleTransform(0.97, 0.97);
  168. popupCard = new Border {
  169. Background = backgroundBrush,
  170. BorderBrush = borderBrush,
  171. BorderThickness = new Thickness(1),
  172. CornerRadius = new CornerRadius(8),
  173. MaxWidth = 700,
  174. SnapsToDevicePixels = true,
  175. UseLayoutRounding = true,
  176. RenderTransform = popupScale,
  177. RenderTransformOrigin = new Point(0, 0),
  178. Effect = new DropShadowEffect {
  179. Opacity = shadowOpacity,
  180. BlurRadius = shadowRadius,
  181. ShadowDepth = 0,
  182. Color = Colors.Black
  183. }
  184. };
  185. var root = new Grid {
  186. Margin = new Thickness(shadowRadius + 1),
  187. SnapsToDevicePixels = true,
  188. UseLayoutRounding = true
  189. };
  190. root.Children.Add(popupCard);
  191. popup = new Popup {
  192. AllowsTransparency = true,
  193. IsHitTestVisible = false,
  194. StaysOpen = true,
  195. PopupAnimation = PopupAnimation.None,
  196. Placement = PlacementMode.Relative,
  197. Child = root
  198. };
  199. }
  200. private static void UpdatePosition(FrameworkElement owner, Point point) {
  201. popup!.PlacementTarget = owner;
  202. popup.HorizontalOffset = Math.Round(point.X + 25);
  203. popup.VerticalOffset = Math.Round(point.Y + 20);
  204. }
  205. private static void Animate(double opacity, double scale, EventHandler? completed) {
  206. var opacityAnimation = new DoubleAnimation(opacity, new Duration(animationTime)) {
  207. EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
  208. };
  209. if (completed is not null) opacityAnimation.Completed += completed;
  210. var scaleAnimation = new DoubleAnimation(scale, new Duration(animationTime)) {
  211. EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
  212. };
  213. popupCard!.BeginAnimation(UIElement.OpacityProperty, opacityAnimation, HandoffBehavior.SnapshotAndReplace);
  214. popupScale!.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation, HandoffBehavior.SnapshotAndReplace);
  215. popupScale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation, HandoffBehavior.SnapshotAndReplace);
  216. }
  217. }