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

时间:2022-08-26 21:28:13

如下:

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))
);
}
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(, , , );
tb.Width = ;
tb.MaxHeight = ;
tb.TextAlignment = TextAlignment.Center;
tb.Style = (Style)Utils.CommonFunctions.LoadResource("CardBody_TextStyle");
tb.TextTrimming = TextTrimming.WordEllipsis;
tb.TextWrapping = TextWrapping.Wrap;
tb.OneLineHeight = ;
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="" Height="" MaxHeight="" Background="Gray" OneLineHeight=""/>

新方法:

<TextBlock Text="Demo" ui:TextBlockAutoToolTip.Enabled="True"/>
var textBlock = new TextBlock { Text = "Demo" };
TextBlockAutoToolTip.SetEnabled(textBlock, true);
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media; namespace Unclassified.UI
{
/// <summary>
/// Shows a ToolTip over a TextBlock when its text is trimmed.
/// </summary>
public class TextBlockAutoToolTip
{
/// <summary>
/// The Enabled attached property.
/// </summary>
public static readonly DependencyProperty EnabledProperty = DependencyProperty.RegisterAttached(
"Enabled",
typeof(bool),
typeof(TextBlockAutoToolTip),
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnAutoToolTipEnabledChanged))); /// <summary>
/// Sets the Enabled attached property on a TextBlock control.
/// </summary>
/// <param name="dependencyObject">The TextBlock control.</param>
/// <param name="enabled">The value.</param>
public static void SetEnabled(DependencyObject dependencyObject, bool enabled)
{
dependencyObject.SetValue(EnabledProperty, enabled);
} private static readonly TrimmedTextBlockVisibilityConverter ttbvc = new TrimmedTextBlockVisibilityConverter(); private static void OnAutoToolTipEnabledChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
TextBlock textBlock = dependencyObject as TextBlock;
if (textBlock != null)
{
bool enabled = (bool)args.NewValue;
if (enabled)
{
var toolTip = new ToolTip
{
Placement = System.Windows.Controls.Primitives.PlacementMode.Relative,
VerticalOffset = -,
HorizontalOffset = -,
Padding = new Thickness(, , , ),
Background = Brushes.White
};
toolTip.SetBinding(UIElement.VisibilityProperty, new System.Windows.Data.Binding
{
RelativeSource = new System.Windows.Data.RelativeSource(System.Windows.Data.RelativeSourceMode.Self),
Path = new PropertyPath("PlacementTarget"),
Converter = ttbvc
});
toolTip.SetBinding(ContentControl.ContentProperty, new System.Windows.Data.Binding
{
RelativeSource = new System.Windows.Data.RelativeSource(System.Windows.Data.RelativeSourceMode.Self),
Path = new PropertyPath("PlacementTarget.Text")
});
toolTip.SetBinding(Control.ForegroundProperty, new System.Windows.Data.Binding
{
RelativeSource = new System.Windows.Data.RelativeSource(System.Windows.Data.RelativeSourceMode.Self),
Path = new PropertyPath("PlacementTarget.Foreground")
});
textBlock.ToolTip = toolTip;
textBlock.TextTrimming = TextTrimming.CharacterEllipsis;
}
}
} private class TrimmedTextBlockVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var textBlock = value as TextBlock;
if (textBlock == null)
return Visibility.Collapsed; Typeface typeface = new Typeface(
textBlock.FontFamily,
textBlock.FontStyle,
textBlock.FontWeight,
textBlock.FontStretch); // FormattedText is used to measure the whole width of the text held up by TextBlock container
FormattedText formattedText = new FormattedText(
textBlock.Text,
System.Threading.Thread.CurrentThread.CurrentCulture,
textBlock.FlowDirection,
typeface,
textBlock.FontSize,
textBlock.Foreground); formattedText.MaxTextWidth = textBlock.ActualWidth; // When the maximum text width of the FormattedText instance is set to the actual
// width of the textBlock, if the textBlock is being trimmed to fit then the formatted
// text will report a larger height than the textBlock. Should work whether the
// textBlock is single or multi-line.
// The width check detects if any single line is too long to fit within the text area,
// this can only happen if there is a long span of text with no spaces.
bool isTrimmed = formattedText.Height > textBlock.ActualHeight ||
formattedText.MinWidth > formattedText.MaxTextWidth; return isTrimmed ? Visibility.Visible : Visibility.Collapsed;
} public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
}

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&sol;TextBlock 文本超出显示时,文本靠右显示

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

  4. 背水一战 Windows 10 &lpar;104&rpar; - 通知(Toast)&colon; 纯文本 toast&comma; 短时 toast&comma; 长时 toast&comma; 图文 toast

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

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

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

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

    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. ps 实例部分

    实例篇1:将不同图片通过阀值转换成黑白色人物头像 图像-黑白-曲向-阀值 本图像-复制-粘贴

  2. 从&OpenCurlyDoubleQuote;差不多了”到 正式发布 -- 新浪微博WinPhone UWP版诞生记

    本文粗略记述了UWP团队从接手新浪微博项目到发布第一版的过程.本文不是技术贴,而是回顾“软件工程周期失控是一种怎样的体验”. 接手新项目:捡了个大便宜 2016年1月份,UWP team开始接手新浪微 ...

  3. Bat脚本实现MySQL数据库SQL文件备份

    @echo offecho 在线兑奖系统自动备份脚本(请勿关闭) 联系人:  电话::loopset /a "FDate=%date:~,4%%date:~5,2%%date:~8,2%&q ...

  4. listView异步处理图片下载缓存

    package cn.wangmeng.test; import java.io.File;import java.io.FileOutputStream;import java.io.IOExcep ...

  5. javascript的getter和setter(转)

    显然这是一个无关IE(高级IE除外)的话题,尽管如此,有兴趣的同学还是一起来认识一下ECMAScript5标准中getter和setter的实现.在一个对象中,操作其中的属性或方法,通常运用最多的就是 ...

  6. (一)DOM 常用操作 —— &OpenCurlyDoubleQuote;查找”节点

    在 DOM 树中,如果想要操作一个节点,那么首先要"查找"到这个节点.查找节点的方法由 Document 接口定义,而该接口由 JavaScript 中的 document 对象实 ...

  7. 老师博客copy -高阶函数2

    新闻 管理   Py西游攻关之函数   一 函数是什么? 函数一词来源于数学,但编程中的「函数」概念,与数学中的函数是有很大不同的,具体区别,我们后面会讲,编程中的函数在英文中也有很多不同的叫法.在B ...

  8. back-to-top回到顶部

    function backTop(back) { back.hide(); $(window).scroll(function () { $(window).scrollTop() > 0 ? ...

  9. 清理本地Maven仓库

    目录 1.清理target 2.清理该项目依赖的本地仓库中的maven包 3.清理maven本地仓库中下载失败的包 参考: 1.清理target mvn clean -U 2.清理该项目依赖的本地仓库 ...

  10. lsof &vert;grep deleted&semi;du -sh &sol; &semi;df -h&semi;

    有台机器磁盘满了: 进程端口都正常,存活:但是页面却完全打不开了: 日志爆满:删除日志后: 在根上 du -sh * 然后 df -h 发现差别太大了: du -sh * / 才不足7G: df -h ...