ModernTooltipService.cs 18 KB

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