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

//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);
            }
        }
    }

猜你喜欢

转载自www.cnblogs.com/dahe1993/p/12945261.html