ModernTooltipService.cs 15 KB

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