ModernTooltipService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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.5);
  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 readonly DispatcherTimer leaveWatchTimer = new() { Interval = TimeSpan.FromMilliseconds(50) };
  55. private const int leaveWatchMissLimit = 2;
  56. private static bool initialized;
  57. private static int animationToken;
  58. private static int leaveWatchMissCount;
  59. private static Point lastMousePoint;
  60. private static Popup? popup;
  61. private static Border? popupCard;
  62. private static ScaleTransform? popupScale;
  63. private static FrameworkElement? currentOwner;
  64. private static ToolTip? borrowedToolTip;
  65. private static object? borrowedContent;
  66. static ModernTooltipService() {
  67. openTimer.Tick += (_, _) => {
  68. openTimer.Stop();
  69. if (currentOwner is not null) Show(currentOwner, lastMousePoint);
  70. };
  71. leaveWatchTimer.Tick += (_, _) => {
  72. if (currentOwner is null) {
  73. leaveWatchTimer.Stop();
  74. return;
  75. }
  76. if (!TryGetMousePoint(currentOwner, out var point)) {
  77. Close(true);
  78. return;
  79. }
  80. lastMousePoint = point;
  81. if (GetFollowMouse(currentOwner) && popup is { IsOpen: true }) UpdatePosition(currentOwner, point);
  82. if (IsMouseRelatedToOwner(currentOwner)) {
  83. leaveWatchMissCount = 0;
  84. if (currentOwner.IsEnabled) leaveWatchTimer.Stop();
  85. return;
  86. }
  87. if (++leaveWatchMissCount >= leaveWatchMissLimit) Close(true);
  88. };
  89. }
  90. #endregion
  91. #region 全局鼠标事件
  92. private static void OnMouseEnter(object sender, MouseEventArgs e) {
  93. if (sender is not FrameworkElement owner || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out _, out _)) return;
  94. if (ReferenceEquals(currentOwner, owner) && popup is { IsOpen: true }) {
  95. leaveWatchTimer.Stop();
  96. return;
  97. }
  98. if (owner is ComboBox comboBox) HookComboBoxDropDown(comboBox);
  99. if (!ReferenceEquals(currentOwner, owner)) HideImmediately();
  100. currentOwner = owner;
  101. lastMousePoint = e.GetPosition(owner);
  102. openTimer.Stop();
  103. leaveWatchTimer.Stop();
  104. var delay = Math.Max(0, ToolTipService.GetInitialShowDelay(owner));
  105. if (delay == 0) {
  106. Show(owner, lastMousePoint);
  107. } else {
  108. openTimer.Interval = TimeSpan.FromMilliseconds(delay);
  109. openTimer.Start();
  110. }
  111. }
  112. private static void OnMouseMove(object sender, MouseEventArgs e) {
  113. if (sender is not FrameworkElement owner || !ReferenceEquals(owner, currentOwner)) return;
  114. lastMousePoint = e.GetPosition(owner);
  115. if (GetFollowMouse(owner) && popup is { IsOpen: true }) UpdatePosition(owner, lastMousePoint);
  116. }
  117. private static void OnMouseLeave(object sender, MouseEventArgs e) {
  118. if (sender is not FrameworkElement owner || !ReferenceEquals(owner, currentOwner)) return;
  119. // TextBox 点击时,内部元素可能短暂捕获鼠标并触发一次假的 MouseLeave。
  120. // 若确认鼠标还在控件内,则短暂轮询;避免 WPF 不再补发真正 MouseLeave 时 Tooltip 残留。
  121. owner.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => {
  122. if (!ReferenceEquals(owner, currentOwner)) return;
  123. if (!TryGetMousePoint(owner, out var point)) {
  124. Close(true);
  125. return;
  126. }
  127. lastMousePoint = point;
  128. if (GetFollowMouse(owner) && popup is { IsOpen: true }) UpdatePosition(owner, point);
  129. if (IsMouseRelatedToOwner(owner)) {
  130. leaveWatchMissCount = 0;
  131. leaveWatchTimer.Stop();
  132. return;
  133. }
  134. leaveWatchMissCount = 0;
  135. leaveWatchTimer.Start();
  136. }));
  137. }
  138. // 坐标仍在控件内只说明需要复核;最终是否保留还要看 WPF 命中或捕获是否属于该控件树。
  139. private static bool TryGetMousePoint(FrameworkElement owner, out Point point) {
  140. point = default;
  141. if (!owner.IsLoaded || !owner.IsVisible) return false;
  142. point = Mouse.GetPosition(owner);
  143. return point.X >= 0 && point.Y >= 0 && point.X <= owner.ActualWidth && point.Y <= owner.ActualHeight;
  144. }
  145. private static bool IsMouseRelatedToOwner(FrameworkElement owner) {
  146. if (owner.IsMouseOver) return true;
  147. if (!owner.IsEnabled && ToolTipService.GetShowOnDisabled(owner) && TryGetMousePoint(owner, out _)) return true;
  148. if (IsInOwnerTree(Mouse.DirectlyOver as DependencyObject, owner)) return true;
  149. return IsInOwnerTree(Mouse.Captured as DependencyObject, owner);
  150. }
  151. private static bool IsInOwnerTree(DependencyObject? element, DependencyObject owner) {
  152. while (element is not null) {
  153. if (ReferenceEquals(element, owner)) return true;
  154. var visualParent = element is Visual or Visual3D ? VisualTreeHelper.GetParent(element) : null;
  155. element = visualParent ?? LogicalTreeHelper.GetParent(element);
  156. }
  157. return false;
  158. }
  159. #endregion
  160. #region Tooltip 生命周期
  161. private static bool CanShowModernTooltip(FrameworkElement owner) {
  162. return GetUseModernTooltip(owner) && ToolTipService.GetIsEnabled(owner) && (owner.IsEnabled || ToolTipService.GetShowOnDisabled(owner));
  163. }
  164. private static void OnToolTipOpening(object sender, ToolTipEventArgs e) {
  165. if (sender is not FrameworkElement owner || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out _, out _)) return;
  166. e.Handled = true;
  167. if (owner.IsEnabled) return;
  168. if (!ReferenceEquals(currentOwner, owner)) HideImmediately();
  169. currentOwner = owner;
  170. openTimer.Stop();
  171. leaveWatchTimer.Stop();
  172. lastMousePoint = Mouse.GetPosition(owner);
  173. Show(owner, lastMousePoint);
  174. leaveWatchMissCount = 0;
  175. leaveWatchTimer.Start();
  176. }
  177. private static bool TryGetToolTip(FrameworkElement owner, out object? content, out ToolTip? sourceToolTip) {
  178. var raw = owner.ToolTip;
  179. sourceToolTip = raw as ToolTip;
  180. content = sourceToolTip?.Content ?? raw;
  181. return content is not null && (content is not string text || text.Length > 0);
  182. }
  183. private static void Show(FrameworkElement owner, Point point) {
  184. if (!ReferenceEquals(owner, currentOwner) || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out var content, out var sourceToolTip)) return;
  185. EnsurePopup();
  186. popup!.PlacementTarget = owner;
  187. popupCard!.DataContext = sourceToolTip?.DataContext ?? owner.DataContext;
  188. popupCard.FlowDirection = owner.FlowDirection;
  189. UpdatePosition(owner, point);
  190. popupCard.Child = null;
  191. RestoreBorrowedContent();
  192. // 如果原 ToolTip.Content 是 Visual/FrameworkElement,必须先从原 ToolTip 借出,
  193. // 否则同一个元素会同时拥有两个逻辑父级,导致 WPF 抛异常。
  194. if (sourceToolTip is not null && content is DependencyObject contentObject && ReferenceEquals(LogicalTreeHelper.GetParent(contentObject), sourceToolTip)) {
  195. borrowedToolTip = sourceToolTip;
  196. borrowedContent = content;
  197. sourceToolTip.Content = null;
  198. }
  199. popupCard.Child = content is string stringContent && sourceToolTip?.ContentTemplate is null && sourceToolTip?.ContentTemplateSelector is null
  200. ? new TextBlock {
  201. Text = stringContent, TextWrapping = TextWrapping.Wrap, Foreground = foregroundBrush, Margin = contentMargin,
  202. FontSize = 12.5, LineHeight = 17, MaxWidth = 676 }
  203. : new ContentPresenter {
  204. Content = content, ContentTemplate = sourceToolTip?.ContentTemplate, ContentTemplateSelector = sourceToolTip?.ContentTemplateSelector,
  205. ContentStringFormat = sourceToolTip?.ContentStringFormat, Margin = contentMargin, MaxWidth = 676 };
  206. animationToken++;
  207. popupCard.Opacity = 0;
  208. popupScale!.ScaleX = 0.97; popupScale.ScaleY = 0.97;
  209. popup.IsOpen = true;
  210. Animate(1, 1, null);
  211. }
  212. private static void Close(bool animated) {
  213. openTimer.Stop();
  214. leaveWatchTimer.Stop();
  215. currentOwner = null;
  216. if (popup is null || popupCard is null) return;
  217. if (!popup.IsOpen || !animated) {
  218. HideImmediately();
  219. return;
  220. }
  221. var token = ++animationToken;
  222. Animate(0, 0.97, (_, _) => {
  223. if (token != animationToken) return;
  224. HideImmediately();
  225. });
  226. }
  227. private static void HideImmediately() {
  228. openTimer.Stop();
  229. leaveWatchTimer.Stop();
  230. animationToken++;
  231. if (popup is not null) popup.IsOpen = false;
  232. if (popupCard is not null) {
  233. popupCard.BeginAnimation(UIElement.OpacityProperty, null);
  234. popupCard.Child = null;
  235. }
  236. if (popupScale is not null) {
  237. popupScale.BeginAnimation(ScaleTransform.ScaleXProperty, null);
  238. popupScale.BeginAnimation(ScaleTransform.ScaleYProperty, null);
  239. }
  240. RestoreBorrowedContent();
  241. }
  242. private static void RestoreBorrowedContent() {
  243. if (borrowedToolTip is null) return;
  244. borrowedToolTip.Content = borrowedContent;
  245. borrowedToolTip = null;
  246. borrowedContent = null;
  247. }
  248. #endregion
  249. #region Popup 创建、定位与动画
  250. private static void EnsurePopup() {
  251. if (popup is not null) return;
  252. popupScale = new ScaleTransform(0.97, 0.97);
  253. popupCard = new Border {
  254. Background = backgroundBrush, BorderBrush = borderBrush, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(8),
  255. MaxWidth = 700, SnapsToDevicePixels = true, UseLayoutRounding = true,
  256. RenderTransform = popupScale, RenderTransformOrigin = new Point(0, 0),
  257. Effect = new DropShadowEffect { Opacity = shadowOpacity, BlurRadius = shadowRadius, ShadowDepth = 0, Color = Colors.Black } };
  258. var root = new Grid { Margin = new Thickness(shadowRadius + 1), SnapsToDevicePixels = true, UseLayoutRounding = true };
  259. root.Children.Add(popupCard);
  260. popup = new Popup {
  261. AllowsTransparency = true, IsHitTestVisible = false, StaysOpen = true, PopupAnimation = PopupAnimation.None,
  262. Placement = PlacementMode.Relative, Child = root };
  263. }
  264. private static void UpdatePosition(FrameworkElement owner, Point point) {
  265. popup!.PlacementTarget = owner;
  266. popup.HorizontalOffset = Math.Round(point.X + 15);
  267. popup.VerticalOffset = Math.Round(point.Y + 25);
  268. }
  269. private static void Animate(double opacity, double scale, EventHandler? completed) {
  270. var opacityAnimation = new DoubleAnimation(opacity, new Duration(animationTime)) {
  271. EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
  272. };
  273. if (completed is not null) opacityAnimation.Completed += completed;
  274. var scaleAnimation = new DoubleAnimation(scale, new Duration(animationTime)) {
  275. EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseOut }
  276. };
  277. popupCard!.BeginAnimation(UIElement.OpacityProperty, opacityAnimation, HandoffBehavior.SnapshotAndReplace);
  278. popupScale!.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation, HandoffBehavior.SnapshotAndReplace);
  279. popupScale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation, HandoffBehavior.SnapshotAndReplace);
  280. }
  281. #endregion
  282. // WPF 原生 Tooltip 会在 ComboBox 下拉弹出时关闭;这里保持同样行为。
  283. private static void HookComboBoxDropDown(ComboBox? comboBox) {
  284. if (comboBox is null || (bool) comboBox.GetValue(IsComboBoxDropDownHookedProperty)) return;
  285. comboBox.SetValue(IsComboBoxDropDownHookedProperty, true);
  286. comboBox.DropDownOpened += static (_, _) => { if (currentOwner is not null) Close(true); };
  287. }
  288. }