ModernTooltipService.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. // 此文件主体由 AI 生成,应作为独立模块,尽量减少与其他内容的耦合。
  2. // 使用 ModernTooltipService 接管后,TooltipService 仅有 IsEnabled、ShowOnDisabled、InitialShowDelay 仍然有效,其他属性不再生效。
  3. using System.ComponentModel;
  4. using System.Windows;
  5. using System.Windows.Controls;
  6. using System.Windows.Controls.Primitives;
  7. using System.Windows.Input;
  8. using System.Windows.Media;
  9. using System.Windows.Media.Animation;
  10. using System.Windows.Media.Effects;
  11. using System.Windows.Media.Media3D;
  12. using System.Windows.Threading;
  13. namespace MeloongCore.Wpf;
  14. public static class ModernTooltipService {
  15. // 控制是否使用现代化 Tooltip 渲染;默认为 true。是否允许显示 Tooltip 仍由 ToolTipService.IsEnabled 控制。
  16. public static void SetUseModernTooltip(DependencyObject element, bool value) => element.SetValue(UseModernTooltipProperty, value);
  17. public static bool GetUseModernTooltip(DependencyObject element) => (bool) element.GetValue(UseModernTooltipProperty);
  18. // 控制 Tooltip 是否跟随鼠标移动;默认为 true。
  19. public static void SetFollowMouse(DependencyObject element, bool value) => element.SetValue(FollowMouseProperty, value);
  20. public static bool GetFollowMouse(DependencyObject element) => (bool) element.GetValue(FollowMouseProperty);
  21. /// <summary>
  22. /// 全局启用现代 Tooltip。启用后会接管所有 <see cref="FrameworkElement.ToolTip"/>。
  23. /// </summary>
  24. internal static void Init() {
  25. if (initialized) return;
  26. initialized = true;
  27. EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.MouseEnterEvent, new MouseEventHandler(OnMouseEnter), true);
  28. EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.MouseMoveEvent, new MouseEventHandler(OnMouseMove), true);
  29. EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.MouseLeaveEvent, new MouseEventHandler(OnMouseLeave), true);
  30. EventManager.RegisterClassHandler(typeof(FrameworkElement), UIElement.PreviewMouseUpEvent, new MouseButtonEventHandler(OnPreviewMouseUp), true);
  31. EventManager.RegisterClassHandler(typeof(FrameworkElement), ToolTipService.ToolTipOpeningEvent, new ToolTipEventHandler(OnToolTipOpening), true);
  32. EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.UnloadedEvent, new RoutedEventHandler(static (sender, _) => {
  33. if (sender is FrameworkElement owner && ReferenceEquals(owner, currentOwner)) Close(false);
  34. }), true);
  35. // Loaded 负责常规路径;PreviewMouseDown 兜底处理 Init 晚于控件 Loaded 的情况。
  36. EventManager.RegisterClassHandler(typeof(ComboBox), FrameworkElement.LoadedEvent, new RoutedEventHandler(static (sender, _) => HookComboBoxDropDown(sender as ComboBox)), true);
  37. EventManager.RegisterClassHandler(typeof(ComboBox), UIElement.PreviewMouseDownEvent, new MouseButtonEventHandler(static (sender, _) => HookComboBoxDropDown(sender as ComboBox)), true);
  38. }
  39. #region 字段与属性
  40. // 附加属性
  41. public static readonly DependencyProperty UseModernTooltipProperty = DependencyProperty.RegisterAttached(
  42. "UseModernTooltip", typeof(bool), typeof(ModernTooltipService), new PropertyMetadata(true));
  43. public static readonly DependencyProperty FollowMouseProperty = DependencyProperty.RegisterAttached(
  44. "FollowMouse", typeof(bool), typeof(ModernTooltipService), new PropertyMetadata(true));
  45. private static readonly DependencyProperty IsComboBoxDropDownHookedProperty = DependencyProperty.RegisterAttached(
  46. "IsComboBoxDropDownHooked", typeof(bool), typeof(ModernTooltipService), new PropertyMetadata(false));
  47. // 常量
  48. private const double closedScale = 0.97;
  49. private const int shadowRadius = 18, contentMaxWidth = 676;
  50. private static readonly Thickness contentMargin = new(12, 11, 12, 8);
  51. private static readonly Brush backgroundBrush = new SolidColorBrush(Colors.White);
  52. private static readonly Brush borderBrush = new SolidColorBrush(Color.FromRgb(0xD6, 0xD6, 0xD6));
  53. private static readonly Brush foregroundBrush = new SolidColorBrush(Color.FromRgb(0x52, 0x52, 0x52));
  54. private static readonly DependencyPropertyDescriptor toolTipPropertyDescriptor =
  55. DependencyPropertyDescriptor.FromProperty(FrameworkElement.ToolTipProperty, typeof(FrameworkElement));
  56. // 状态字段
  57. private static readonly DispatcherTimer openTimer = new();
  58. private static bool initialized;
  59. private static int animationToken;
  60. private static Point lastMousePoint;
  61. private static Popup? popup;
  62. private static Border? popupCard;
  63. private static ScaleTransform? popupScale;
  64. private static FrameworkElement? currentOwner;
  65. private static FrameworkElement? observedToolTipOwner;
  66. private static ToolTip? borrowedToolTip;
  67. private static object? borrowedContent;
  68. static ModernTooltipService() {
  69. backgroundBrush.Freeze();
  70. borderBrush.Freeze();
  71. foregroundBrush.Freeze();
  72. openTimer.Tick += (_, _) => {
  73. openTimer.Stop();
  74. if (currentOwner is not null) Show(currentOwner, lastMousePoint);
  75. };
  76. }
  77. #endregion
  78. #region 事件入口
  79. private static void OnMouseEnter(object sender, MouseEventArgs e) {
  80. if (sender is not FrameworkElement reference) return;
  81. reference.Dispatcher.BeginInvoke(new Action(() => RefreshCurrentOwner(reference)), DispatcherPriority.Input);
  82. }
  83. private static void OnMouseMove(object sender, MouseEventArgs e) {
  84. if (sender is not FrameworkElement reference) return;
  85. if (Mouse.LeftButton == MouseButtonState.Pressed) {
  86. if (currentOwner is FrameworkElement pressedOwner) {
  87. lastMousePoint = Mouse.GetPosition(pressedOwner);
  88. if (GetFollowMouse(pressedOwner) && popup is { IsOpen: true }) {
  89. UpdatePosition(pressedOwner, lastMousePoint);
  90. }
  91. } else if (popup is { IsOpen: true, PlacementTarget: FrameworkElement popupOwner } && GetFollowMouse(popupOwner)) {
  92. lastMousePoint = Mouse.GetPosition(popupOwner);
  93. UpdatePosition(popupOwner, lastMousePoint);
  94. }
  95. return;
  96. }
  97. RefreshCurrentOwner(reference);
  98. if (currentOwner is FrameworkElement owner) {
  99. lastMousePoint = Mouse.GetPosition(owner);
  100. if (GetFollowMouse(owner) && popup is { IsOpen: true }) UpdatePosition(owner, lastMousePoint);
  101. return;
  102. }
  103. if (popup is { IsOpen: true, PlacementTarget: FrameworkElement closingOwner } && GetFollowMouse(closingOwner)) {
  104. lastMousePoint = Mouse.GetPosition(closingOwner);
  105. UpdatePosition(closingOwner, lastMousePoint);
  106. }
  107. }
  108. private static void OnMouseLeave(object sender, MouseEventArgs e) {
  109. if (sender is not FrameworkElement owner || !ReferenceEquals(owner, currentOwner)) return;
  110. if (!(owner.IsEnabled || !ToolTipService.GetShowOnDisabled(owner) || !IsPointInside(owner, Mouse.GetPosition(owner)))) return;
  111. var nextOwner = FindCurrentTooltipOwner(owner);
  112. if (nextOwner is not null && !ReferenceEquals(nextOwner, owner)) {
  113. BeginShow(nextOwner, Mouse.GetPosition(nextOwner));
  114. return;
  115. }
  116. Close(true);
  117. }
  118. private static void OnPreviewMouseUp(object sender, MouseButtonEventArgs e) {
  119. if (sender is not FrameworkElement reference) return;
  120. reference.Dispatcher.BeginInvoke(new Action(() => RefreshCurrentOwner(reference)), DispatcherPriority.Input);
  121. }
  122. private static void OnToolTipOpening(object sender, ToolTipEventArgs e) {
  123. if (sender is not FrameworkElement owner || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out _, out _)) return;
  124. e.Handled = true;
  125. if (ShouldSuppressTooltip(owner)) {
  126. Close(false);
  127. return;
  128. }
  129. // 启用状态控件走 MouseEnter 延迟逻辑;禁用控件只能从原生 Opening 事件接管。
  130. if (owner.IsEnabled) return;
  131. if (!ReferenceEquals(currentOwner, owner)) HideImmediately();
  132. currentOwner = owner;
  133. openTimer.Stop();
  134. lastMousePoint = Mouse.GetPosition(owner);
  135. Show(owner, lastMousePoint);
  136. }
  137. #endregion
  138. #region Tooltip 目标解析
  139. private static void RefreshCurrentOwner(FrameworkElement reference) {
  140. var owner = FindCurrentTooltipOwner(reference);
  141. if (currentOwner is { IsEnabled: false } disabledOwner &&
  142. ToolTipService.GetShowOnDisabled(disabledOwner) &&
  143. IsPointInside(disabledOwner, Mouse.GetPosition(disabledOwner))) {
  144. return;
  145. }
  146. if (ShouldSuppressTooltip(owner)) {
  147. // 鼠标捕获仍在当前拥有者分支内时,保留现有气泡,避免拖选或按压时闪烁。
  148. if (currentOwner is not null &&
  149. Mouse.Captured is DependencyObject captured &&
  150. IsSameTreeBranch(captured, currentOwner) &&
  151. IsPointInside(currentOwner, Mouse.GetPosition(currentOwner))) {
  152. return;
  153. }
  154. Close(false);
  155. return;
  156. }
  157. if (owner is not null) {
  158. BeginShow(owner, Mouse.GetPosition(owner));
  159. } else if (currentOwner is not null) {
  160. Close(true); // 弹窗遮挡等情况可能不会触发原拥有者的 MouseLeave,需要由其他元素收到的 MouseMove 主动关闭
  161. }
  162. }
  163. private static FrameworkElement? FindCurrentTooltipOwner(FrameworkElement reference) {
  164. static FrameworkElement? FindOwnerInAncestors(DependencyObject? start) {
  165. for (var current = start; current is not null; current = GetParent(current)) {
  166. if (current is FrameworkElement owner && CanShowModernTooltip(owner) && TryGetToolTip(owner, out _, out _)) {
  167. return owner;
  168. }
  169. }
  170. return null;
  171. }
  172. var owner = FindOwnerInAncestors(Mouse.DirectlyOver as DependencyObject);
  173. if (owner is not null) return owner;
  174. // 重新从窗口根元素命中测试,避免弹窗出现后 Mouse.DirectlyOver 尚未刷新,继续命中已被遮挡的旧元素。
  175. if (PresentationSource.FromVisual(reference)?.RootVisual is UIElement root) {
  176. var rootHit = root.InputHitTest(Mouse.GetPosition(root)) as DependencyObject;
  177. owner = FindOwnerInAncestors(rootHit);
  178. if (owner is not null) return owner;
  179. if (rootHit is not null && !IsSameTreeBranch(rootHit, reference)) return null;
  180. }
  181. return reference.InputHitTest(Mouse.GetPosition(reference)) is DependencyObject hit
  182. ? FindOwnerInAncestors(hit)
  183. : null;
  184. }
  185. private static bool CanShowModernTooltip(FrameworkElement owner) =>
  186. GetUseModernTooltip(owner) && ToolTipService.GetIsEnabled(owner) && (owner.IsEnabled || ToolTipService.GetShowOnDisabled(owner));
  187. private static bool TryGetToolTip(FrameworkElement owner, out object? content, out ToolTip? sourceToolTip) {
  188. var raw = owner.ToolTip;
  189. sourceToolTip = raw as ToolTip;
  190. content = sourceToolTip is null
  191. ? raw
  192. : sourceToolTip.Content ?? (ReferenceEquals(sourceToolTip, borrowedToolTip) ? borrowedContent : null);
  193. return content is not null && (content is not string text || text.Length > 0);
  194. }
  195. private static bool ShouldSuppressTooltip(FrameworkElement? owner) {
  196. if (Mouse.LeftButton == MouseButtonState.Pressed || Mouse.Captured is null) return false;
  197. if (Mouse.Captured is not DependencyObject captured) return true;
  198. if (owner is null) return true;
  199. return !IsSameTreeBranch(captured, owner);
  200. }
  201. private static bool IsPointInside(FrameworkElement owner, Point point) =>
  202. point.X >= 0 && point.Y >= 0 && point.X <= owner.ActualWidth && point.Y <= owner.ActualHeight;
  203. private static bool IsSameTreeBranch(DependencyObject first, DependencyObject second) {
  204. if (ReferenceEquals(first, second)) return true;
  205. for (var current = GetParent(second); current is not null; current = GetParent(current)) {
  206. if (ReferenceEquals(current, first)) return true;
  207. }
  208. for (var current = GetParent(first); current is not null; current = GetParent(current)) {
  209. if (ReferenceEquals(current, second)) return true;
  210. }
  211. return false;
  212. }
  213. private static DependencyObject? GetParent(DependencyObject current) {
  214. if (current is Visual or Visual3D && VisualTreeHelper.GetParent(current) is { } visualParent) return visualParent;
  215. return LogicalTreeHelper.GetParent(current);
  216. }
  217. #endregion
  218. #region 显示生命周期
  219. private static void BeginShow(FrameworkElement owner, Point point) {
  220. if (!CanShowModernTooltip(owner) || !TryGetToolTip(owner, out _, out _)) return;
  221. if (ShouldSuppressTooltip(owner)) {
  222. Close(false);
  223. return;
  224. }
  225. if (owner is ComboBox comboBox) HookComboBoxDropDown(comboBox);
  226. if (ReferenceEquals(currentOwner, owner)) {
  227. lastMousePoint = point;
  228. if (popup is not { IsOpen: true } && !openTimer.IsEnabled) StartOpenTimer(owner);
  229. return;
  230. }
  231. HideImmediately();
  232. currentOwner = owner;
  233. lastMousePoint = point;
  234. StartOpenTimer(owner);
  235. }
  236. private static void StartOpenTimer(FrameworkElement owner) {
  237. openTimer.Stop();
  238. var delay = Math.Max(0, ToolTipService.GetInitialShowDelay(owner));
  239. if (delay == 0) {
  240. Show(owner, lastMousePoint);
  241. return;
  242. }
  243. openTimer.Interval = TimeSpan.FromMilliseconds(delay);
  244. openTimer.Start();
  245. }
  246. private static void Show(FrameworkElement owner, Point point) {
  247. if (!ReferenceEquals(owner, currentOwner) || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out var content, out var sourceToolTip)) return;
  248. // 禁用控件由原生 ToolTipOpening 确认命中,无法通过常规 InputHitTest 可靠地重新定位。
  249. if (owner.IsEnabled && !ReferenceEquals(owner, FindCurrentTooltipOwner(owner))) {
  250. Close(false);
  251. return;
  252. }
  253. if (popup is null) {
  254. popupScale = new ScaleTransform(closedScale, closedScale);
  255. popupCard = new Border {
  256. Background = backgroundBrush, BorderBrush = borderBrush, BorderThickness = new(1),
  257. CornerRadius = new(8), MaxWidth = 700, SnapsToDevicePixels = true, UseLayoutRounding = true,
  258. RenderTransform = popupScale, RenderTransformOrigin = new(0, 0),
  259. Effect = new DropShadowEffect { Opacity = 0.15, BlurRadius = shadowRadius, ShadowDepth = 0, Color = Colors.Black }
  260. };
  261. var root = new Grid { Margin = new(shadowRadius + 1), SnapsToDevicePixels = true, UseLayoutRounding = true };
  262. root.Children.Add(popupCard);
  263. popup = new Popup {
  264. AllowsTransparency = true, IsHitTestVisible = false, StaysOpen = true, PopupAnimation = PopupAnimation.None,
  265. Placement = PlacementMode.Relative, Child = root
  266. };
  267. }
  268. popup.PlacementTarget = owner;
  269. UpdatePosition(owner, point);
  270. ObserveToolTip(owner);
  271. UpdateContent(owner, content!, sourceToolTip);
  272. animationToken++;
  273. popupCard!.Opacity = 0;
  274. popupScale!.ScaleX = closedScale;
  275. popupScale.ScaleY = closedScale;
  276. popup.IsOpen = true;
  277. Animate(1, 1, null);
  278. }
  279. private static void UpdateContent(FrameworkElement owner, object content, ToolTip? sourceToolTip) {
  280. popupCard!.DataContext = sourceToolTip?.DataContext ?? owner.DataContext;
  281. popupCard.FlowDirection = owner.FlowDirection;
  282. // 先还原上一次借出的 Visual,再挂载新的内容,避免同一元素拥有两个逻辑父级。
  283. popupCard.Child = null;
  284. RestoreBorrowedContent();
  285. if (sourceToolTip is not null && content is DependencyObject contentObject && ReferenceEquals(LogicalTreeHelper.GetParent(contentObject), sourceToolTip)) {
  286. borrowedToolTip = sourceToolTip;
  287. borrowedContent = content;
  288. sourceToolTip.Content = null;
  289. }
  290. var hasTemplate = sourceToolTip?.ContentTemplate is not null || sourceToolTip?.ContentTemplateSelector is not null;
  291. popupCard.Child = content is string stringContent && !hasTemplate
  292. ? new TextBlock {
  293. Text = stringContent, TextWrapping = TextWrapping.Wrap, Foreground = foregroundBrush,
  294. Margin = contentMargin, FontSize = 12.5, LineHeight = 17, MaxWidth = contentMaxWidth
  295. }
  296. : new ContentPresenter {
  297. Content = content, ContentTemplate = sourceToolTip?.ContentTemplate, ContentTemplateSelector = sourceToolTip?.ContentTemplateSelector,
  298. ContentStringFormat = sourceToolTip?.ContentStringFormat, Margin = contentMargin, MaxWidth = contentMaxWidth
  299. };
  300. }
  301. private static void ObserveToolTip(FrameworkElement owner) {
  302. if (ReferenceEquals(observedToolTipOwner, owner)) return;
  303. StopObservingToolTip();
  304. observedToolTipOwner = owner;
  305. toolTipPropertyDescriptor.AddValueChanged(owner, OnToolTipChanged);
  306. }
  307. private static void StopObservingToolTip() {
  308. if (observedToolTipOwner is null) return;
  309. toolTipPropertyDescriptor.RemoveValueChanged(observedToolTipOwner, OnToolTipChanged);
  310. observedToolTipOwner = null;
  311. }
  312. private static void OnToolTipChanged(object? sender, EventArgs e) {
  313. if (sender is not FrameworkElement owner || !ReferenceEquals(owner, currentOwner) || popup is not { IsOpen: true }) return;
  314. if (!CanShowModernTooltip(owner) || !TryGetToolTip(owner, out var content, out var sourceToolTip)) {
  315. Close(true);
  316. return;
  317. }
  318. UpdateContent(owner, content!, sourceToolTip);
  319. }
  320. private static void Close(bool animated) {
  321. openTimer.Stop();
  322. currentOwner = null;
  323. StopObservingToolTip();
  324. if (popup is not { IsOpen: true } || popupCard is null || !animated) {
  325. HideImmediately();
  326. return;
  327. }
  328. var token = ++animationToken;
  329. Animate(0, closedScale, (_, _) => {
  330. if (token != animationToken) return;
  331. HideImmediately();
  332. });
  333. }
  334. private static void HideImmediately() {
  335. openTimer.Stop();
  336. animationToken++;
  337. StopObservingToolTip();
  338. if (popup is not null) popup.IsOpen = false;
  339. if (popupCard is not null) {
  340. popupCard.BeginAnimation(UIElement.OpacityProperty, null);
  341. popupCard.Child = null;
  342. }
  343. if (popupScale is not null) {
  344. popupScale.BeginAnimation(ScaleTransform.ScaleXProperty, null);
  345. popupScale.BeginAnimation(ScaleTransform.ScaleYProperty, null);
  346. }
  347. RestoreBorrowedContent();
  348. }
  349. private static void RestoreBorrowedContent() {
  350. if (borrowedToolTip is null) return;
  351. borrowedToolTip.Content = borrowedContent;
  352. borrowedToolTip = null;
  353. borrowedContent = null;
  354. }
  355. #endregion
  356. #region Popup 渲染与动画
  357. private static void UpdatePosition(FrameworkElement owner, Point point) {
  358. popup!.PlacementTarget = owner;
  359. popup.HorizontalOffset = Math.Round(point.X + 15);
  360. popup.VerticalOffset = Math.Round(point.Y + 25);
  361. }
  362. private static void Animate(double opacity, double scale, EventHandler? completed) {
  363. var duration = new Duration(TimeSpan.FromMilliseconds(70));
  364. var opacityAnimation = new DoubleAnimation(opacity, duration) {
  365. EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
  366. };
  367. if (completed is not null) opacityAnimation.Completed += completed;
  368. var scaleAnimation = new DoubleAnimation(scale, duration) {
  369. EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
  370. };
  371. popupCard!.BeginAnimation(UIElement.OpacityProperty, opacityAnimation, HandoffBehavior.SnapshotAndReplace);
  372. popupScale!.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation, HandoffBehavior.SnapshotAndReplace);
  373. popupScale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation, HandoffBehavior.SnapshotAndReplace);
  374. }
  375. #endregion
  376. // WPF 原生 Tooltip 会在 ComboBox 下拉弹出时关闭;这里保持同样行为。
  377. private static void HookComboBoxDropDown(ComboBox? comboBox) {
  378. if (comboBox is null || (bool) comboBox.GetValue(IsComboBoxDropDownHookedProperty)) return;
  379. comboBox.SetValue(IsComboBoxDropDownHookedProperty, true);
  380. comboBox.DropDownOpened += static (_, _) => { if (currentOwner is not null) Close(true); };
  381. }
  382. }