How to judge text block is trimming with ...
- I have set text block TextTrimming property to WordEllipsis. And i only want to show tooltip when the text block does not show the whole text.
Currently, i used the following mehtod, but the precision is not too good.
FormattedText fText = new FormattedText(txtBlock.Text, System.Globalization.CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(txtBlock.FontFamily, txtBlock.FontStyle, txtBlock.FontWeight, txtBlock.FontStretch), txtBlock.FontSize, Brushes.Black); Rect desiredRect = fText.BuildGeometry(new Point(0, 0)).Bounds; double desiredWidth = desiredRect.Width + (txtBlock.ActualHeight - desiredRect.Height) - 1; if (desiredWidth > txtBlock.ActualWidth) { //... }
anders06
解答
- I think you could use the following extension method to determine if a specified TextBlock has been trimmed without calling BuildGeometry() to get the size of the underlying geomtrical metrics which could be different from my personal experience:
public static class TextBlockExtensions
{
public static Boolean IsTextTrimmed(this 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 formmatedText = new FormattedText(
textBlock.Text,
System.Threading.Thread.CurrentThread.CurrentCulture,
textBlock.FlowDirection,
typeface,
textBlock.FontSize,
textBlock.Foreground);
return formmatedText.Width > textBlock.Width;
}
}
- 已標示為解答Marco Zhou 2008年9月3日 上午 09:53
所有回覆
- Any suggestion?
anders06 - I think you could use the following extension method to determine if a specified TextBlock has been trimmed without calling BuildGeometry() to get the size of the underlying geomtrical metrics which could be different from my personal experience:
public static class TextBlockExtensions
{
public static Boolean IsTextTrimmed(this 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 formmatedText = new FormattedText(
textBlock.Text,
System.Threading.Thread.CurrentThread.CurrentCulture,
textBlock.FlowDirection,
typeface,
textBlock.FontSize,
textBlock.Foreground);
return formmatedText.Width > textBlock.Width;
}
}
- 已標示為解答Marco Zhou 2008年9月3日 上午 09:53
- Thanks, Marco.
It works so perfect.
And it should be "return formmatedText.Width > textBlock.ActualWidth;“ :)
anders06

