如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows.Controls;
  7. using System.Windows.Media;
  8. using System.Windows;
  9. using System.Globalization;
  10.  
  11. namespace XXXX
  12. {
  13. public class TooltipTextBlock : TextBlock
  14. {
  15. static TooltipTextBlock()
  16. {
  17. OneLineHeightProperty =
  18. DependencyProperty.Register(
  19. "OneLineHeight",
  20. typeof(double),
  21. typeof(TooltipTextBlock),
  22. new FrameworkPropertyMetadata((double))
  23. );
  24. }
  25. protected override void OnToolTipOpening(ToolTipEventArgs e)
  26. {
  27. if (TextTrimming != TextTrimming.None)
  28. {
  29. e.Handled = !IsTextTrimmed();
  30. }
  31. }
  32.  
  33. private bool IsTextTrimmed()
  34. {
  35. var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch);
  36. var formattedText = new FormattedText(Text, CultureInfo.CurrentCulture, FlowDirection, typeface, FontSize, Foreground);
  37. double lineHeight = OneLineHeight;//formattedText.Height;
  38. double totalWidth = formattedText.Width;
  39.  
  40. int lines = (int)Math.Ceiling(totalWidth / ActualWidth);
  41.  
  42. return (lines * lineHeight > MaxHeight);
  43. }
  44. public double OneLineHeight
  45. {
  46. get { return (double)GetValue(OneLineHeightProperty); }
  47. set { SetValue(OneLineHeightProperty, value); }
  48. }
  49.  
  50. public static readonly DependencyProperty OneLineHeightProperty;
  51. }
  52. }

使用:

  1. TooltipTextBlock tb = new TooltipTextBlock();
  2. tb.Margin = new Thickness(, , , );
  3. tb.Width = ;
  4. tb.MaxHeight = ;
  5. tb.TextAlignment = TextAlignment.Center;
  6. tb.Style = (Style)Utils.CommonFunctions.LoadResource("CardBody_TextStyle");
  7. tb.TextTrimming = TextTrimming.WordEllipsis;
  8. tb.TextWrapping = TextWrapping.Wrap;
  9. tb.OneLineHeight = ;
  10. ToolTip tt = new ToolTip() { Content = des, };
  11. tb.ToolTip = tt;

或:

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

新方法:

  1. <TextBlock Text="Demo" ui:TextBlockAutoToolTip.Enabled="True"/>
  1. var textBlock = new TextBlock { Text = "Demo" };
  2. TextBlockAutoToolTip.SetEnabled(textBlock, true);
  1. using System;
  2. using System.Globalization;
  3. using System.Windows;
  4. using System.Windows.Controls;
  5. using System.Windows.Data;
  6. using System.Windows.Media;
  7.  
  8. namespace Unclassified.UI
  9. {
  10. /// <summary>
  11. /// Shows a ToolTip over a TextBlock when its text is trimmed.
  12. /// </summary>
  13. public class TextBlockAutoToolTip
  14. {
  15. /// <summary>
  16. /// The Enabled attached property.
  17. /// </summary>
  18. public static readonly DependencyProperty EnabledProperty = DependencyProperty.RegisterAttached(
  19. "Enabled",
  20. typeof(bool),
  21. typeof(TextBlockAutoToolTip),
  22. new FrameworkPropertyMetadata(new PropertyChangedCallback(OnAutoToolTipEnabledChanged)));
  23.  
  24. /// <summary>
  25. /// Sets the Enabled attached property on a TextBlock control.
  26. /// </summary>
  27. /// <param name="dependencyObject">The TextBlock control.</param>
  28. /// <param name="enabled">The value.</param>
  29. public static void SetEnabled(DependencyObject dependencyObject, bool enabled)
  30. {
  31. dependencyObject.SetValue(EnabledProperty, enabled);
  32. }
  33.  
  34. private static readonly TrimmedTextBlockVisibilityConverter ttbvc = new TrimmedTextBlockVisibilityConverter();
  35.  
  36. private static void OnAutoToolTipEnabledChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
  37. {
  38. TextBlock textBlock = dependencyObject as TextBlock;
  39. if (textBlock != null)
  40. {
  41. bool enabled = (bool)args.NewValue;
  42. if (enabled)
  43. {
  44. var toolTip = new ToolTip
  45. {
  46. Placement = System.Windows.Controls.Primitives.PlacementMode.Relative,
  47. VerticalOffset = -,
  48. HorizontalOffset = -,
  49. Padding = new Thickness(, , , ),
  50. Background = Brushes.White
  51. };
  52. toolTip.SetBinding(UIElement.VisibilityProperty, new System.Windows.Data.Binding
  53. {
  54. RelativeSource = new System.Windows.Data.RelativeSource(System.Windows.Data.RelativeSourceMode.Self),
  55. Path = new PropertyPath("PlacementTarget"),
  56. Converter = ttbvc
  57. });
  58. toolTip.SetBinding(ContentControl.ContentProperty, new System.Windows.Data.Binding
  59. {
  60. RelativeSource = new System.Windows.Data.RelativeSource(System.Windows.Data.RelativeSourceMode.Self),
  61. Path = new PropertyPath("PlacementTarget.Text")
  62. });
  63. toolTip.SetBinding(Control.ForegroundProperty, new System.Windows.Data.Binding
  64. {
  65. RelativeSource = new System.Windows.Data.RelativeSource(System.Windows.Data.RelativeSourceMode.Self),
  66. Path = new PropertyPath("PlacementTarget.Foreground")
  67. });
  68. textBlock.ToolTip = toolTip;
  69. textBlock.TextTrimming = TextTrimming.CharacterEllipsis;
  70. }
  71. }
  72. }
  73.  
  74. private class TrimmedTextBlockVisibilityConverter : IValueConverter
  75. {
  76. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  77. {
  78. var textBlock = value as TextBlock;
  79. if (textBlock == null)
  80. return Visibility.Collapsed;
  81.  
  82. Typeface typeface = new Typeface(
  83. textBlock.FontFamily,
  84. textBlock.FontStyle,
  85. textBlock.FontWeight,
  86. textBlock.FontStretch);
  87.  
  88. // FormattedText is used to measure the whole width of the text held up by TextBlock container
  89. FormattedText formattedText = new FormattedText(
  90. textBlock.Text,
  91. System.Threading.Thread.CurrentThread.CurrentCulture,
  92. textBlock.FlowDirection,
  93. typeface,
  94. textBlock.FontSize,
  95. textBlock.Foreground);
  96.  
  97. formattedText.MaxTextWidth = textBlock.ActualWidth;
  98.  
  99. // When the maximum text width of the FormattedText instance is set to the actual
  100. // width of the textBlock, if the textBlock is being trimmed to fit then the formatted
  101. // text will report a larger height than the textBlock. Should work whether the
  102. // textBlock is single or multi-line.
  103. // The width check detects if any single line is too long to fit within the text area,
  104. // this can only happen if there is a long span of text with no spaces.
  105. bool isTrimmed = formattedText.Height > textBlock.ActualHeight ||
  106. formattedText.MinWidth > formattedText.MaxTextWidth;
  107.  
  108. return isTrimmed ? Visibility.Visible : Visibility.Collapsed;
  109. }
  110.  
  111. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  112. {
  113. throw new NotImplementedException();
  114. }
  115. }
  116. }
  117. }

TextBlock 重写,当文本过长时,自动截断文本并出现Tooltip的更多相关文章

  1. HTML中文本过长时自动隐藏末尾部分或中间等任意部分

    一.    一般情况下,HTML字符串过长时都会将超过的部分隐藏点,方法如下: 设置CSS: .ellipsis-type{ max-width: 50px;                      ...

  2. css实现文本过长时自动添加省略号

    1. 效果 2. Html <div id="main_app_content" class="container"> <div class= ...

  3. WPF TextBox/TextBlock 文本超出显示时,文本靠右显示

    文本框显示 文本框正常显示: 文本框超出区域显示: 实现方案 判断文本框是否超出区域 请见<TextBlock IsTextTrimmed 判断文本是否超出> 设置文本布局显示 1. Fl ...

  4. 背水一战 Windows 10 (104) - 通知(Toast): 纯文本 toast, 短时 toast, 长时 toast, 图文 toast

    [源码下载] 背水一战 Windows 10 (104) - 通知(Toast): 纯文本 toast, 短时 toast, 长时 toast, 图文 toast 作者:webabcd 介绍背水一战 ...

  5. (转)完美解决 Android WebView 文本框获取焦点后自动放大有关问题

    完美解决 Android WebView 文本框获取焦点后自动放大问题 前几天在写一个项目时,要求在项目中嵌入一个WebView 本来很快就完成了,测试也没有问题.但发给新加坡时,他们测试都会出现文本 ...

  6. python基础语法13 内置模块 subprocess,re模块,logging日志记录模块,防止导入模块时自动执行测试功能,包的理论

    subprocess模块: - 可以通过python代码给操作系统终端发送命令, 并且可以返回结果. sub: 子    process: 进程 import subprocess while Tru ...

  7. 关于angularJS绑定数据时自动转义html标签

    关于angularJS绑定数据时自动转义html标签 angularJS在进行数据绑定时默认是会以文本的形式输出,也就是对你数据中的html标签不进行转义照单全收,这样提高了安全性,防止了html标签 ...

  8. android脚步---自动完成文本框

    自动完成文本框AutoCompleteTextView,当用户输入一定字符时,自动完成文本框会显示一个下拉菜单,供用户选择,设置一个Adapter,该Adapter中封装了AutoCompleteTe ...

  9. Android 文字过长TextView如何自动截断并显示成省略号

    当用TextView来显示标题的时候,如果标题内容过长的话,我们不希望其换行显示,这时候我们需要其自动截断,超过的部分显示成省略号. 如下图所示,标题过长,自动换行了,显示不是很好看. 这时候我们需要 ...

随机推荐

  1. 微信小程序一些总结

    1.体验版和线上是啥区别,啥关系 在微信开发者工具里提交代码后进入体验版,在微信后台里点击版本管理,就可以看到线上版本,和开发体验版,描述里有提交备注. 在体验版里发布审核之后会进入到线上.他们两个可 ...

  2. WinForm—串口通讯

    ialPort(串行端口资源) 常用属性: BaudRate 此串行端口上要使用的波特率 DataBits 每发送/接收一个字节的数据位数目 DtrEnable 在通讯过程中是否启用数据终端就绪(St ...

  3. Liunx-history命令

    1. 查看历史命令执行记录 2. 查看命令cd 的历史执行记录 3. 执行历史记录中,序号为1的命令

  4. http2.0之头部压缩

    什么是头部压缩?为什么要头部压缩? 我们知道,http请求和响应都是由[状态行.请求/响应头部.消息主题]三部分组成的. 一般而言,消息主体都会经过gzip压缩,或者本身传输的就是压缩过后的二进制文件 ...

  5. rabbitmq实现一台服务器同时给所有的consumer发送消息(tp框架)(第四篇)

    之前的学习了把消息直接publish到queue里面,然后consume掉, 真实的情况,我们会把消息先发送到exchange里面,由它来处理,是发给某一个队列,还是发给某些队列,还是丢弃掉? exc ...

  6. elasticsearch(二) 之 elasticsearch安装

    目录 elasticsearch 安装与配置 安装java 安装elastcsearch 二进制安装(tar包) 在进入生产之前我们必须要考虑到以下设置 增大打开文件句柄数量 禁用虚拟内存 合适配置的 ...

  7. Linux-(tar,gzip,df,du)

    tar命令 首先要弄清两个概念:打包和压缩.打包是指将一大堆文件或目录变成一个总的文件:压缩则是将一个大的文件通过一些压缩算法变成一个小文件. 为什么要区分这两个概念呢?这源于Linux中很多压缩程序 ...

  8. HihoCoder - 1040 矩形判断

    矩形判断 给出平面上4条线段,判断这4条线段是否恰好围成一个面积大于0的矩形. Input 输入第一行是一个整数T(1<=T<=100),代表测试数据的数量. 每组数据包含4行,每行包含4 ...

  9. SpringMvc注解开发

    1.四大注解的定义 (1)Controller注解:该注解使用在一个类上面,参数为value,值为访问该controller的名称,默认为空,如果为空 则值为该controller类名的首字母小写的值 ...

  10. 使用vue2+Axios+Router 之后的总结以及遇到的一些坑

    构建 vue有自己的脚手架构建工具vue-cli,使用起来非常方便,使用webpack来集成各种开发便捷工具,比如: 代码热更新,修改代码之后网页无刷新改变,对前端开发来说非常的方便 PostCss, ...