且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF TextBlock IsTextTrimmed 判断文本是否超出

更新时间:2022-09-24 19:42:55

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