如果文字太长,我该如何自动显示工具提示?

时间:2014-02-06 22:37:03

标签: xaml windows-runtime windows-store-apps tooltip winrt-xaml

在Windows应用商店应用中,我有以下TextBlock:

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

当文本太长而没有省略号时,如何自动显示工具提示?

2 个答案:

答案 0 :(得分:1)

以下是我的解决方案,基于thisthis

首先,创建一个附加属性以启用自动工具提示:

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

然后像这样在XAML中使用它:

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

只有在修剪文本块时才会显示工具提示。

答案 1 :(得分:0)

通常你点击它并打开一个完全显示的视图,因为它有更多的空间/使用更小的字体或文本包装/滚动。