1. 程式人生 > >TextBlock 重寫,當文本過長時,自動截斷文本並出現Tooltip

TextBlock 重寫,當文本過長時,自動截斷文本並出現Tooltip

XML oca center res clr des glob ner edi

如下:

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