原文: 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、文本替換等。