标签: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