ModernTooltipService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. // 此文件主体由 AI 生成,应作为独立模块,尽量减少与其他内容的耦合。
  2. // 使用 ModernTooltipService 接管后,TooltipService 仅有 IsEnabled、ShowOnDisabled、InitialShowDelay 仍然有效,其他属性不再生效。
  3. using System.Windows;
  4. using System.Windows.Controls;
  5. using System.Windows.Controls.Primitives;
  6. using System.Windows.Input;
  7. using System.Windows.Media;
  8. using System.Windows.Media.Animation;
  9. using System.Windows.Media.Effects;
  10. using System.Windows.Threading;
  11. namespace MeloongCore.Wpf;
  12. public static class ModernTooltipService {
  13. // 控制是否使用现代化 Tooltip 渲染;默认为 true。是否允许显示 Tooltip 仍由 ToolTipService.IsEnabled 控制。
  14. public static void SetUseModernTooltip(DependencyObject element, bool value) => element.SetValue(UseModernTooltipProperty, value);
  15. public static bool GetUseModernTooltip(DependencyObject element) => (bool) element.GetValue(UseModernTooltipProperty);
  16. // 控制 Tooltip 是否跟随鼠标移动;默认为 true。
  17. public static void SetFollowMouse(DependencyObject element, bool value) => element.SetValue(FollowMouseProperty, value);
  18. public static bool GetFollowMouse(DependencyObject element) => (bool) element.GetValue(FollowMouseProperty);
  19. // 样式配置
  20. private static readonly TimeSpan animationTime = TimeSpan.FromMilliseconds(70);
  21. private static readonly int shadowRadius = 18;
  22. private static readonly float shadowOpacity = 0.15f;
  23. private static readonly Thickness contentMargin = new(12, 11, 12, 8);
  24. private static readonly Brush backgroundBrush = new SolidColorBrush(Colors.White);
  25. private static readonly Brush borderBrush = new SolidColorBrush(Color.FromRgb(0xD6, 0xD6, 0xD6));
  26. private static readonly Brush foregroundBrush = new SolidColorBrush(Color.FromRgb(0x52, 0x52, 0x52));
  27. /// <summary>
  28. /// 全局启用现代 Tooltip。启用后会接管所有 <see cref="FrameworkElement.ToolTip"/>。
  29. /// </summary>
  30. internal static void Init() {
  31. if (initialized) return;
  32. initialized = true;
  33. EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.MouseEnterEvent, new MouseEventHandler(OnMouseEnter), true);
  34. EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.MouseMoveEvent, new MouseEventHandler(OnMouseMove), true);
  35. EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.MouseLeaveEvent, new MouseEventHandler(OnMouseLeave), true);
  36. EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.UnloadedEvent, new RoutedEventHandler(static (sender, _) => {
  37. if (sender is FrameworkElement owner && ReferenceEquals(owner, currentOwner)) Close(false);
  38. }), true);
  39. EventManager.RegisterClassHandler(typeof(FrameworkElement), ToolTipService.ToolTipOpeningEvent, new ToolTipEventHandler(OnToolTipOpening), true);
  40. // Loaded 负责常规路径;PreviewMouseDown 兜底处理 Init 晚于控件 Loaded 的情况。
  41. EventManager.RegisterClassHandler(typeof(ComboBox), FrameworkElement.LoadedEvent, new RoutedEventHandler(static (sender, _) => HookComboBoxDropDown(sender as ComboBox)), true);
  42. EventManager.RegisterClassHandler(typeof(ComboBox), UIElement.PreviewMouseDownEvent, new MouseButtonEventHandler(static (sender, _) => HookComboBoxDropDown(sender as ComboBox)), true);
  43. }
  44. #region 附加属性与运行状态
  45. // 附加属性
  46. public static readonly DependencyProperty UseModernTooltipProperty = DependencyProperty.RegisterAttached(
  47. "UseModernTooltip", typeof(bool), typeof(ModernTooltipService), new PropertyMetadata(true));
  48. public static readonly DependencyProperty FollowMouseProperty = DependencyProperty.RegisterAttached(
  49. "FollowMouse", typeof(bool), typeof(ModernTooltipService), new PropertyMetadata(true));
  50. private static readonly DependencyProperty IsComboBoxDropDownHookedProperty = DependencyProperty.RegisterAttached(
  51. "IsComboBoxDropDownHooked", typeof(bool), typeof(ModernTooltipService), new PropertyMetadata(false));
  52. private static readonly DispatcherTimer openTimer = new();
  53. private static bool initialized;
  54. private static int animationToken;
  55. private static Point lastMousePoint;
  56. private static Popup? popup;
  57. private static Border? popupCard;
  58. private static ScaleTransform? popupScale;
  59. private static FrameworkElement? currentOwner;
  60. private static ToolTip? borrowedToolTip;
  61. private static object? borrowedContent;
  62. static ModernTooltipService() {
  63. openTimer.Tick += (_, _) => {
  64. openTimer.Stop();
  65. if (currentOwner is not null) Show(currentOwner, lastMousePoint);
  66. };
  67. }
  68. #endregion
  69. #region 全局鼠标事件
  70. private static void OnMouseEnter(object sender, MouseEventArgs e) {
  71. if (sender is not FrameworkElement owner || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out _, out _)) return;
  72. if (ReferenceEquals(currentOwner, owner) && popup is { IsOpen: true }) {
  73. return;
  74. }
  75. if (owner is ComboBox comboBox) HookComboBoxDropDown(comboBox);
  76. if (!ReferenceEquals(currentOwner, owner)) HideImmediately();
  77. currentOwner = owner;
  78. lastMousePoint = e.GetPosition(owner);
  79. openTimer.Stop();
  80. var delay = Math.Max(0, ToolTipService.GetInitialShowDelay(owner));
  81. if (delay == 0) {
  82. Show(owner, lastMousePoint);
  83. } else {
  84. openTimer.Interval = TimeSpan.FromMilliseconds(delay);
  85. openTimer.Start();
  86. }
  87. }
  88. private static void OnMouseMove(object sender, MouseEventArgs e) {
  89. if (sender is not FrameworkElement owner || !ReferenceEquals(owner, currentOwner)) return;
  90. lastMousePoint = e.GetPosition(owner);
  91. if (e.LeftButton == MouseButtonState.Pressed && !IsPointInside(owner, lastMousePoint)) {
  92. Close(true);
  93. return;
  94. }
  95. if (GetFollowMouse(owner) && popup is { IsOpen: true }) UpdatePosition(owner, lastMousePoint);
  96. }
  97. private static void OnMouseLeave(object sender, MouseEventArgs e) {
  98. if (sender is not FrameworkElement owner || !ReferenceEquals(owner, currentOwner)) return;
  99. // 避免 Tooltip 在文本区域长按左键时自动收回
  100. var point = e.GetPosition(owner);
  101. if (e.LeftButton == MouseButtonState.Pressed && IsPointInside(owner, point)) return;
  102. Close(true);
  103. }
  104. private static bool IsPointInside(FrameworkElement owner, Point point) {
  105. return point.X >= 0 && point.Y >= 0 && point.X <= owner.ActualWidth && point.Y <= owner.ActualHeight;
  106. }
  107. #endregion
  108. #region Tooltip 生命周期
  109. private static bool CanShowModernTooltip(FrameworkElement owner) {
  110. return GetUseModernTooltip(owner) && ToolTipService.GetIsEnabled(owner) && (owner.IsEnabled || ToolTipService.GetShowOnDisabled(owner));
  111. }
  112. private static void OnToolTipOpening(object sender, ToolTipEventArgs e) {
  113. if (sender is not FrameworkElement owner || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out _, out _)) return;
  114. e.Handled = true;
  115. if (owner.IsEnabled) return;
  116. if (!ReferenceEquals(currentOwner, owner)) HideImmediately();
  117. currentOwner = owner;
  118. openTimer.Stop();
  119. lastMousePoint = Mouse.GetPosition(owner);
  120. Show(owner, lastMousePoint);
  121. }
  122. private static bool TryGetToolTip(FrameworkElement owner, out object? content, out ToolTip? sourceToolTip) {
  123. var raw = owner.ToolTip;
  124. sourceToolTip = raw as ToolTip;
  125. content = sourceToolTip?.Content ?? raw;
  126. return content is not null && (content is not string text || text.Length > 0);
  127. }
  128. private static void Show(FrameworkElement owner, Point point) {
  129. if (!ReferenceEquals(owner, currentOwner) || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out var content, out var sourceToolTip)) return;
  130. EnsurePopup();
  131. popup!.PlacementTarget = owner;
  132. popupCard!.DataContext = sourceToolTip?.DataContext ?? owner.DataContext;
  133. popupCard.FlowDirection = owner.FlowDirection;
  134. UpdatePosition(owner, point);
  135. popupCard.Child = null;
  136. RestoreBorrowedContent();
  137. // 如果原 ToolTip.Content 是 Visual/FrameworkElement,必须先从原 ToolTip 借出,
  138. // 否则同一个元素会同时拥有两个逻辑父级,导致 WPF 抛异常。
  139. if (sourceToolTip is not null && content is DependencyObject contentObject && ReferenceEquals(LogicalTreeHelper.GetParent(contentObject), sourceToolTip)) {
  140. borrowedToolTip = sourceToolTip;
  141. borrowedContent = content;
  142. sourceToolTip.Content = null;
  143. }
  144. popupCard.Child = content is string stringContent && sourceToolTip?.ContentTemplate is null && sourceToolTip?.ContentTemplateSelector is null
  145. ? new TextBlock {
  146. Text = stringContent, TextWrapping = TextWrapping.Wrap, Foreground = foregroundBrush, Margin = contentMargin,
  147. FontSize = 12.5, LineHeight = 17, MaxWidth = 676 }
  148. : new ContentPresenter {
  149. Content = content, ContentTemplate = sourceToolTip?.ContentTemplate, ContentTemplateSelector = sourceToolTip?.ContentTemplateSelector,
  150. ContentStringFormat = sourceToolTip?.ContentStringFormat, Margin = contentMargin, MaxWidth = 676 };
  151. animationToken++;
  152. popupCard.Opacity = 0;
  153. popupScale!.ScaleX = 0.97; popupScale.ScaleY = 0.97;
  154. popup.IsOpen = true;
  155. Animate(1, 1, null);
  156. }
  157. private static void Close(bool animated) {
  158. openTimer.Stop();
  159. currentOwner = null;
  160. if (popup is null || popupCard is null) return;
  161. if (!popup.IsOpen || !animated) {
  162. HideImmediately();
  163. return;
  164. }
  165. var token = ++animationToken;
  166. Animate(0, 0.97, (_, _) => {
  167. if (token != animationToken) return;
  168. HideImmediately();
  169. });
  170. }
  171. private static void HideImmediately() {
  172. openTimer.Stop();
  173. animationToken++;
  174. if (popup is not null) popup.IsOpen = false;
  175. if (popupCard is not null) {
  176. popupCard.BeginAnimation(UIElement.OpacityProperty, null);
  177. popupCard.Child = null;
  178. }
  179. if (popupScale is not null) {
  180. popupScale.BeginAnimation(ScaleTransform.ScaleXProperty, null);
  181. popupScale.BeginAnimation(ScaleTransform.ScaleYProperty, null);
  182. }
  183. RestoreBorrowedContent();
  184. }
  185. private static void RestoreBorrowedContent() {
  186. if (borrowedToolTip is null) return;
  187. borrowedToolTip.Content = borrowedContent;
  188. borrowedToolTip = null;
  189. borrowedContent = null;
  190. }
  191. #endregion
  192. #region Popup 创建、定位与动画
  193. private static void EnsurePopup() {
  194. if (popup is not null) return;
  195. popupScale = new ScaleTransform(0.97, 0.97);
  196. popupCard = new Border {
  197. Background = backgroundBrush, BorderBrush = borderBrush, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(8),
  198. MaxWidth = 700, SnapsToDevicePixels = true, UseLayoutRounding = true,
  199. RenderTransform = popupScale, RenderTransformOrigin = new Point(0, 0),
  200. Effect = new DropShadowEffect { Opacity = shadowOpacity, BlurRadius = shadowRadius, ShadowDepth = 0, Color = Colors.Black } };
  201. var root = new Grid { Margin = new Thickness(shadowRadius + 1), SnapsToDevicePixels = true, UseLayoutRounding = true };
  202. root.Children.Add(popupCard);
  203. popup = new Popup {
  204. AllowsTransparency = true, IsHitTestVisible = false, StaysOpen = true, PopupAnimation = PopupAnimation.None,
  205. Placement = PlacementMode.Relative, Child = root };
  206. }
  207. private static void UpdatePosition(FrameworkElement owner, Point point) {
  208. popup!.PlacementTarget = owner;
  209. popup.HorizontalOffset = Math.Round(point.X + 15);
  210. popup.VerticalOffset = Math.Round(point.Y + 25);
  211. }
  212. private static void Animate(double opacity, double scale, EventHandler? completed) {
  213. var opacityAnimation = new DoubleAnimation(opacity, new Duration(animationTime)) {
  214. EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
  215. };
  216. if (completed is not null) opacityAnimation.Completed += completed;
  217. var scaleAnimation = new DoubleAnimation(scale, new Duration(animationTime)) {
  218. EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
  219. };
  220. popupCard!.BeginAnimation(UIElement.OpacityProperty, opacityAnimation, HandoffBehavior.SnapshotAndReplace);
  221. popupScale!.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation, HandoffBehavior.SnapshotAndReplace);
  222. popupScale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation, HandoffBehavior.SnapshotAndReplace);
  223. }
  224. #endregion
  225. // WPF 原生 Tooltip 会在 ComboBox 下拉弹出时关闭;这里保持同样行为。
  226. private static void HookComboBoxDropDown(ComboBox? comboBox) {
  227. if (comboBox is null || (bool) comboBox.GetValue(IsComboBoxDropDownHookedProperty)) return;
  228. comboBox.SetValue(IsComboBoxDropDownHookedProperty, true);
  229. comboBox.DropDownOpened += static (_, _) => { if (currentOwner is not null) Close(true); };
  230. }
  231. }