Show Tooltip when text is being trimmed

Viewed 20387
  <TextBlock Width="100" Text="The quick brown fox jumps over the lazy dog" TextTrimming="WordEllipsis">
     <TextBlock.ToolTip>
        <ToolTip DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}">
           <TextBlock Text="{Binding Text}"/>
        </ToolTip>
     </TextBlock.ToolTip>
  </TextBlock>

How can I show the ToolTip only when the text is trimmed? Like the windows desktp shortcut icons.

7 Answers

I used this from @pogosoma but with the CalculateIsTextTrimmed function from @snicker which is perfect

private static void SetTooltipBasedOnTrimmingState(TextBlock tb)
{
    Typeface typeface = new Typeface(tb.FontFamily, tb.FontStyle, tb.FontWeight, tb.FontStretch);

    FormattedText formattedText = new FormattedText(tb.Text, System.Threading.Thread.CurrentThread.CurrentCulture, tb.FlowDirection, typeface, tb.FontSize, tb.Foreground)
        { MaxTextWidth = tb.ActualWidth };

    bool isTextTrimmed = (formattedText.Height > tb.ActualHeight || formattedText.MinWidth > formattedText.MaxTextWidth);
    ToolTipService.SetToolTip(tb, isTextTrimmed ? tb.ToolTip : null);
}
Related