xaml - 如果文本太长,如何自动显示工具提示?

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

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

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

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

最佳答案

这是我的解决方案,基于 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" />

工具提示只会在文本 block 被修剪时显示。

关于xaml - 如果文本太长,如何自动显示工具提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21615593/

相关文章:

xaml - UWP/XAML : Larger reveal effect (or gradient customization) on ListView

c# - XAML 数据绑定(bind)到全局变量?

WPF:创建对话框/提示

silverlight - 无法在 xaml 中创建 View 模型实例

notifications - 设置 Win8 定期磁贴通知的到期日期并更新通知 channel

xaml - XAML 中的属性 Duration 不允许值类型 Duration

c# - 在 Windows 商店应用程序中获取窗口宽度/高度

javascript - WinJS 中的音频分析

c# - WinRT 中的集合导航

c# - 使用 Template10 在页面内导航