码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-10-30 16:02:15      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:util   etc   binding   direct   app   meta   maxwidth   readonly   framework   

如下:

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

标签:util   etc   binding   direct   app   meta   maxwidth   readonly   framework   

原文地址:http://www.cnblogs.com/lopengye/p/7754661.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!