WPF TextBlock IsTextTrimmed 判断文本是否超出

WPF TextBlock/TextBox 设置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);bool isTrimmed = formattedText.Width > textBox.Width;
       
return isTrimmed;
     }

 FormattedText:绘制文本,也可以根据当前控件样式(最大高宽/字体样式),获取当前控件的最大容纳字符数。

根据以上属性,可以做很多事,如文本超出时,设置ToolTip、文本替换、文本布局等。

posted @ 2018-05-14 15:53  唐宋元明清2188  阅读(1682)  评论(3编辑  收藏  举报