原文: WPF TextBlock IsTextTrimmed 判断文本是否超出
WPF TextBlock 设置TextTrimming情况下
判断 isTextTrimmed(Text 文本是否超出 是否出现了省略号)
private bool IsTextTrimmed(TextBlock textBlock)
{
Typeface typeface = new Typeface(
textBlock.FontFamily,
textBlock.FontStyle,
textBlock.FontWeight,
textBlock.FontStretch);
FormattedText formattedText = new FormattedText(
textBlock.Text,
System.Threading.Thread.CurrentThread.CurrentCulture,
textBlock.FlowDirection,
typeface,
textBlock.FontSize,
textBlock.Foreground);
formattedText.MaxTextWidth = textBlock.ActualWidth;
bool isTrimmed = formattedText.Height > textBlock.ActualHeight ||
formattedText.Width >textBlock.MaxTextWidth;
return isTrimmed;
}
FormattedText :绘制文本,也可以根据当前控件样式(最大高宽/字体样式),获取当前控件的最大容纳字符数。
根据以上属性,可以做很多事,如文本超出时,设置ToolTip、文本替换等。