【问题标题】:How can I automatically show a tooltip if the text is too long?如果文本太长,如何自动显示工具提示?
【发布时间】:2014-03-04 03:32:12
【问题描述】:

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

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

如果文本太长而无法在没有省略号的情况下显示时,如何自动显示工具提示?

【问题讨论】:

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


    【解决方案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" />
    

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

    【讨论】:

      【解决方案2】:

      通常你点击它并打开一个视图,它会在其中完整显示,因为它有更多的空间/使用较小的字体,或者是文本换行/滚动的地方。

      【讨论】:

      • 这是一个很好的解决方案,但对我来说不是。为简洁起见,我省略了代码,但我的文本块是按钮的内容,点击按钮已经绑定到导航命令。我真的需要悬停时的工具提示,但前提是文本太长而无法在没有省略号的情况下显示
      猜你喜欢
      • 2011-05-19
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      相关资源
      最近更新 更多