如果文本太长,如何自动显示工具提示? [英] How can I automatically show a tooltip if the text is too long?
本文介绍了如果文本太长,如何自动显示工具提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Windows 商店应用程序中,我有以下 TextBlock:
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?
推荐答案
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);
}
}
然后像这样在 XAML 中使用它:
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.
这篇关于如果文本太长,如何自动显示工具提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文