-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
TextBlockAttach.cs
68 lines (59 loc) · 2.43 KB
/
TextBlockAttach.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using HandyControl.Data;
using HandyControl.Tools.Helper;
namespace HandyControl.Controls
{
public class TextBlockAttach
{
public static readonly DependencyProperty AutoTooltipProperty = DependencyProperty.RegisterAttached(
"AutoTooltip", typeof(bool), typeof(TextBlockAttach), new PropertyMetadata(ValueBoxes.FalseBox, OnAutoTooltipChanged));
private static void OnAutoTooltipChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TextBlock ctl)
{
if ((bool) e.NewValue)
{
UpdateTooltip(ctl);
ctl.SizeChanged += TextBlock_SizeChanged;
}
else
{
ctl.SizeChanged -= TextBlock_SizeChanged;
}
}
}
public static void SetAutoTooltip(DependencyObject element, bool value)
=> element.SetValue(AutoTooltipProperty, ValueBoxes.BooleanBox(value));
public static bool GetAutoTooltip(DependencyObject element)
=> (bool) element.GetValue(AutoTooltipProperty);
private static void TextBlock_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (sender is TextBlock textBlock)
{
UpdateTooltip(textBlock);
}
}
private static void UpdateTooltip(TextBlock textBlock)
{
textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
var width = textBlock.DesiredSize.Width - textBlock.Margin.Left - textBlock.Margin.Right;
if(textBlock.RenderSize.Width > width || textBlock.ActualWidth < width || CalcTextWidth(textBlock) > width)
{
ToolTipService.SetToolTip(textBlock, textBlock.Text);
}
else
{
ToolTipService.SetToolTip(textBlock, null);
}
}
private static double CalcTextWidth(TextBlock textBlock)
{
var formattedText = TextHelper.CreateFormattedText(textBlock.Text, textBlock.FlowDirection,
new Typeface(textBlock.FontFamily, textBlock.FontStyle, textBlock.FontWeight, textBlock.FontStretch),
textBlock.FontSize);
return formattedText.WidthIncludingTrailingWhitespace;
}
}
}