这里实现了一个简单的TextBlock的AutoTooltip,Code as Follow:
public sealed class SimpleTextBlockTrimming
{
public static bool GetAutoTooltip( DependencyObject obj)
{
return ( bool)obj.GetValue(AutoTooltipProperty);
}
public static void SetAutoTooltip( DependencyObject obj, bool value)
{
obj.SetValue(AutoTooltipProperty, value);
}
public static readonly DependencyProperty AutoTooltipProperty =
DependencyProperty.RegisterAttached(
"AutoTooltip",
typeof( bool),
typeof( SimpleTextBlockTrimming),
new PropertyMetadata(false , OnAutoTooltipPropertyChanged));
private static void OnAutoTooltipPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBlock = d as TextBlock;
if (textBlock == null)
{
return;
}
if (e.NewValue.Equals( true))
{
textBlock.TextTrimming = TextTrimming.CharacterEllipsis;
textBlock.MouseEnter += textBlock_MouseEnter;
}
else
{
textBlock.MouseEnter -= textBlock_MouseEnter;
}
}
private static void textBlock_MouseEnter( object sender, MouseEventArgs e)
{
var tblock = sender as TextBlock;
if ( null == tblock)
return;
ToolTipService.SetToolTip(tblock, IsTextTrimmed(tblock) ? tblock.Text : null);
}
private static bool IsTextTrimmed( TextBlock textBlock)
{
Typeface typeface = new Typeface(textBlock.FontFamily,
textBlock.FontStyle,
textBlock.FontWeight,
textBlock.FontStretch);
// FormattedText is used to measure the whole width of the text held up by TextBlock container.
FormattedText formattedText = new FormattedText (
textBlock.Text,
System.Threading. Thread.CurrentThread.CurrentCulture,
textBlock.FlowDirection,
typeface,
textBlock.FontSize,
textBlock.Foreground);
return formattedText.Width - textBlock.ActualWidth > 2;
}
}