How can I automatically show a tooltip if the text

2019-07-16 02:43发布

In a Windows Store Application I have the following TextBlock:

        <TextBlock Text="Seriously long text for the purpose of showing tooltip"
                   TextTrimming="CharacterEllipsis" />

How do I automatically show a tooltip when the text is too long to display without an ellipsis?

2条回答
可以哭但决不认输i
2楼-- · 2019-07-16 03:07

Usually you tap it and open a view where it shows up in full either because it has more space/uses smaller font or where the text wraps/scrolls.

查看更多
一夜七次
3楼-- · 2019-07-16 03:12

Here's my solution, based on this and this.

First, create an attached property to enable auto tooltip:

public static class TextBlockUtils {
    public static readonly DependencyProperty AutoTooltipProperty =
        DependencyProperty.RegisterAttached ("AutoTooltip", typeof (bool), typeof (TextBlockUtils),
                                             new PropertyMetadata (false, OnAutoTooltipPropertyChanged));

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

    public static bool GetAutoTooltip (DependencyObject d) {
        return (bool) d.GetValue (AutoTooltipProperty);
    }

    private static void OnAutoTooltipPropertyChanged (DependencyObject d, DependencyPropertyChangedEventArgs e) {
        var tb = d as TextBlock;
        if (tb != null) {
            bool newValue = (bool) e.NewValue;
            if (newValue) {
                SetTooltipBasedOnTrimmingState (tb);
                tb.SizeChanged += OnTextBlockSizeChanged;
            }
            else {
                tb.SizeChanged -= OnTextBlockSizeChanged;
        }
    }

    private static void OnTextBlockSizeChanged (object sender, SizeChangedEventArgs e) {
        var tb = sender as TextBlock;
        if (tb != null) {
            SetTooltipBasedOnTrimmingState (tb);
        }
    }

    private static void SetTooltipBasedOnTrimmingState (TextBlock tb) {
        bool isTextTrimmed = tb.ActualWidth < tb.DesiredSize.Width;
        ToolTipService.SetToolTip (tb, isTextTrimmed ? tb.Text : null);
    }
}

Then use it in XAML like so:

<TextBlock Content="long text"
           TextTrimming="CharacterEllipsis"
           TextBlockUtils.AutoTooltip="True" />

The tooltip will only be shown when the textblock is trimmed.

查看更多
登录 后发表回答