首页 > Windows开发 > 详细

震惊 WPF 两行代码 实现Textblock 文字超出部分加省略号 hover显示全部

时间:2020-05-24 01:22:24      阅读:333      评论:0      收藏:0      [点我收藏+]
//xaml代码
local:TextBlockToolTip.AutoTooltip="True" TextTrimming="CharacterEllipsis"

后台代码:

  public class TextBlockToolTip
    {
        public static bool GetAutoTooltip(DependencyObject obj)
        {
            return (bool)obj.GetValue(AutoTooltipProperty);
        }

        public static void SetAutoTooltip(DependencyObject obj, bool value)
        {
            obj.SetValue(AutoTooltipProperty, value);
        }

        // Using a DependencyProperty as the backing store for AutoTooltip.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AutoTooltipProperty =
            DependencyProperty.RegisterAttached("AutoTooltip", typeof(bool), typeof(TextBlockToolTip), new PropertyMetadata(false, OnAutoTooltipPropertyChanged));

        private static void OnAutoTooltipPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            TextBlock textBlock = d as TextBlock;
            if (textBlock == null)
                return;

            if (e.NewValue.Equals(true))
            {
                textBlock.TextTrimming = TextTrimming.WordEllipsis;
                ComputeAutoTooltip(textBlock);
                textBlock.SizeChanged += TextBlock_SizeChanged;
            }
            else
            {
                textBlock.SizeChanged -= TextBlock_SizeChanged;
            }
        }

        private static void TextBlock_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            TextBlock textBlock = sender as TextBlock;
            ComputeAutoTooltip(textBlock);
        }

        private static void ComputeAutoTooltip(TextBlock textBlock)
        {
            textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            var width = textBlock.DesiredSize.Width;

            if (textBlock.ActualWidth < width)
            {
                ToolTipService.SetToolTip(textBlock, textBlock.Text);
            }
            else
            {
                ToolTipService.SetToolTip(textBlock, null);
            }
        }
    }

 

震惊 WPF 两行代码 实现Textblock 文字超出部分加省略号 hover显示全部

原文:https://www.cnblogs.com/dahe1993/p/12945261.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!