2
0

ModernTooltipService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 (GetFollowMouse(owner) && popup is { IsOpen: true }) UpdatePosition(owner, lastMousePoint);
  92. }
  93. private static void OnMouseLeave(object sender, MouseEventArgs e) {
  94. if (sender is not FrameworkElement owner || !ReferenceEquals(owner, currentOwner)) return;
  95. Close(true);
  96. }
  97. #endregion
  98. #region Tooltip 生命周期
  99. private static bool CanShowModernTooltip(FrameworkElement owner) {
  100. return GetUseModernTooltip(owner) && ToolTipService.GetIsEnabled(owner) && (owner.IsEnabled || ToolTipService.GetShowOnDisabled(owner));
  101. }
  102. private static void OnToolTipOpening(object sender, ToolTipEventArgs e) {
  103. if (sender is not FrameworkElement owner || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out _, out _)) return;
  104. e.Handled = true;
  105. if (owner.IsEnabled) return;
  106. if (!ReferenceEquals(currentOwner, owner)) HideImmediately();
  107. currentOwner = owner;
  108. openTimer.Stop();
  109. lastMousePoint = Mouse.GetPosition(owner);
  110. Show(owner, lastMousePoint);
  111. }
  112. private static bool TryGetToolTip(FrameworkElement owner, out object? content, out ToolTip? sourceToolTip) {
  113. var raw = owner.ToolTip;
  114. sourceToolTip = raw as ToolTip;
  115. content = sourceToolTip?.Content ?? raw;
  116. return content is not null && (content is not string text || text.Length > 0);
  117. }
  118. private static void Show(FrameworkElement owner, Point point) {
  119. if (!ReferenceEquals(owner, currentOwner) || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out var content, out var sourceToolTip)) return;
  120. EnsurePopup();
  121. popup!.PlacementTarget = owner;
  122. popupCard!.DataContext = sourceToolTip?.DataContext ?? owner.DataContext;
  123. popupCard.FlowDirection = owner.FlowDirection;
  124. UpdatePosition(owner, point);
  125. popupCard.Child = null;
  126. RestoreBorrowedContent();
  127. // 如果原 ToolTip.Content 是 Visual/FrameworkElement,必须先从原 ToolTip 借出,
  128. // 否则同一个元素会同时拥有两个逻辑父级,导致 WPF 抛异常。
  129. if (sourceToolTip is not null && content is DependencyObject contentObject && ReferenceEquals(LogicalTreeHelper.GetParent(contentObject), sourceToolTip)) {
  130. borrowedToolTip = sourceToolTip;
  131. borrowedContent = content;
  132. sourceToolTip.Content = null;
  133. }
  134. popupCard.Child = content is string stringContent && sourceToolTip?.ContentTemplate is null && sourceToolTip?.ContentTemplateSelector is null
  135. ? new TextBlock {
  136. Text = stringContent, TextWrapping = TextWrapping.Wrap, Foreground = foregroundBrush, Margin = contentMargin,
  137. FontSize = 12.5, LineHeight = 17, MaxWidth = 676 }
  138. : new ContentPresenter {
  139. Content = content, ContentTemplate = sourceToolTip?.ContentTemplate, ContentTemplateSelector = sourceToolTip?.ContentTemplateSelector,
  140. ContentStringFormat = sourceToolTip?.ContentStringFormat, Margin = contentMargin, MaxWidth = 676 };
  141. animationToken++;
  142. popupCard.Opacity = 0;
  143. popupScale!.ScaleX = 0.97; popupScale.ScaleY = 0.97;
  144. popup.IsOpen = true;
  145. Animate(1, 1, null);
  146. }
  147. private static void Close(bool animated) {
  148. openTimer.Stop();
  149. currentOwner = null;
  150. if (popup is null || popupCard is null) return;
  151. if (!popup.IsOpen || !animated) {
  152. HideImmediately();
  153. return;
  154. }
  155. var token = ++animationToken;
  156. Animate(0, 0.97, (_, _) => {
  157. if (token != animationToken) return;
  158. HideImmediately();
  159. });
  160. }
  161. private static void HideImmediately() {
  162. openTimer.Stop();
  163. animationToken++;
  164. if (popup is not null) popup.IsOpen = false;
  165. if (popupCard is not null) {
  166. popupCard.BeginAnimation(UIElement.OpacityProperty, null);
  167. popupCard.Child = null;
  168. }
  169. if (popupScale is not null) {
  170. popupScale.BeginAnimation(ScaleTransform.ScaleXProperty, null);
  171. popupScale.BeginAnimation(ScaleTransform.ScaleYProperty, null);
  172. }
  173. RestoreBorrowedContent();
  174. }
  175. private static void RestoreBorrowedContent() {
  176. if (borrowedToolTip is null) return;
  177. borrowedToolTip.Content = borrowedContent;
  178. borrowedToolTip = null;
  179. borrowedContent = null;
  180. }
  181. #endregion
  182. #region Popup 创建、定位与动画
  183. private static void EnsurePopup() {
  184. if (popup is not null) return;
  185. popupScale = new ScaleTransform(0.97, 0.97);
  186. popupCard = new Border {
  187. Background = backgroundBrush, BorderBrush = borderBrush, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(8),
  188. MaxWidth = 700, SnapsToDevicePixels = true, UseLayoutRounding = true,
  189. RenderTransform = popupScale, RenderTransformOrigin = new Point(0, 0),
  190. Effect = new DropShadowEffect { Opacity = shadowOpacity, BlurRadius = shadowRadius, ShadowDepth = 0, Color = Colors.Black } };
  191. var root = new Grid { Margin = new Thickness(shadowRadius + 1), SnapsToDevicePixels = true, UseLayoutRounding = true };
  192. root.Children.Add(popupCard);
  193. popup = new Popup {
  194. AllowsTransparency = true, IsHitTestVisible = false, StaysOpen = true, PopupAnimation = PopupAnimation.None,
  195. Placement = PlacementMode.Relative, Child = root };
  196. }
  197. private static void UpdatePosition(FrameworkElement owner, Point point) {
  198. popup!.PlacementTarget = owner;
  199. popup.HorizontalOffset = Math.Round(point.X + 15);
  200. popup.VerticalOffset = Math.Round(point.Y + 25);
  201. }
  202. private static void Animate(double opacity, double scale, EventHandler? completed) {
  203. var opacityAnimation = new DoubleAnimation(opacity, new Duration(animationTime)) {
  204. EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
  205. };
  206. if (completed is not null) opacityAnimation.Completed += completed;
  207. var scaleAnimation = new DoubleAnimation(scale, new Duration(animationTime)) {
  208. EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
  209. };
  210. popupCard!.BeginAnimation(UIElement.OpacityProperty, opacityAnimation, HandoffBehavior.SnapshotAndReplace);
  211. popupScale!.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation, HandoffBehavior.SnapshotAndReplace);
  212. popupScale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation, HandoffBehavior.SnapshotAndReplace);
  213. }
  214. #endregion
  215. // WPF 原生 Tooltip 会在 ComboBox 下拉弹出时关闭;这里保持同样行为。
  216. private static void HookComboBoxDropDown(ComboBox? comboBox) {
  217. if (comboBox is null || (bool) comboBox.GetValue(IsComboBoxDropDownHookedProperty)) return;
  218. comboBox.SetValue(IsComboBoxDropDownHookedProperty, true);
  219. comboBox.DropDownOpened += static (_, _) => { if (currentOwner is not null) Close(true); };
  220. }
  221. }