TextBlock 重写,当文本过长时,自动截断文本并出现Tooltip

Posted lopengye

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TextBlock 重写,当文本过长时,自动截断文本并出现Tooltip相关的知识,希望对你有一定的参考价值。

如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows;
using System.Globalization;

namespace XXXX
{
    public class TooltipTextBlock : TextBlock
    {
        static TooltipTextBlock()
        {
            OneLineHeightProperty =
            DependencyProperty.Register(
                "OneLineHeight",
                typeof(double),
                typeof(TooltipTextBlock),
                new FrameworkPropertyMetadata((double)16)
                );
        }
        protected override void OnToolTipOpening(ToolTipEventArgs e)
        {
            if (TextTrimming != TextTrimming.None)
            {
                e.Handled = !IsTextTrimmed();
            }
        }

        private bool IsTextTrimmed()
        {
            var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch);
            var formattedText = new FormattedText(Text, CultureInfo.CurrentCulture, FlowDirection, typeface, FontSize, Foreground);
            double lineHeight = OneLineHeight;//formattedText.Height;
            double totalWidth = formattedText.Width;

            int lines = (int)Math.Ceiling(totalWidth / ActualWidth);

            return (lines * lineHeight > MaxHeight);
        }
        public double OneLineHeight
        {
            get { return (double)GetValue(OneLineHeightProperty); }
            set { SetValue(OneLineHeightProperty, value); }
        }

        public static readonly DependencyProperty OneLineHeightProperty;
    }
}

使用:

            TooltipTextBlock tb = new TooltipTextBlock();
            tb.Margin = new Thickness(0, 23, 0, 0);
            tb.Width = 280;
            tb.MaxHeight = 97;
            tb.TextAlignment = TextAlignment.Center;
            tb.Style = (Style)Utils.CommonFunctions.LoadResource("CardBody_TextStyle");
            tb.TextTrimming = TextTrimming.WordEllipsis;
            tb.TextWrapping = TextWrapping.Wrap;
            tb.OneLineHeight = 24;
            ToolTip tt = new ToolTip() { Content = des, };
            tb.ToolTip = tt;    

或:

xmlns:local="clr-namespace:Test"
<local:TooltipTextBlock Text="This is some text lafsdk jflklakjsd " TextWrapping="Wrap"
    TextTrimming="WordEllipsis"
    ToolTip="{Binding Text,RelativeSource={RelativeSource Self}}"
    MaxWidth="80" Height="80" MaxHeight="80" Background="Gray" OneLineHeight="50"/>

 

以上是关于TextBlock 重写,当文本过长时,自动截断文本并出现Tooltip的主要内容,如果未能解决你的问题,请参考以下文章

JDBC插入数据超长时无法自动截断问题

DotNetBar 的Label控件,当Text文本过长时,自动换行

访问:文本在报告中 Can Grow=Yes 的文本框显示中被截断

MFC - 当最大化子窗口的标题很长时,MDI 主框架标题被截断

更改文本截断行为

TextBlock 的重写样式的奇怪行为