這是我今天在回答SO問題時偶然遇到的,以爲可能還比較通用,就記錄下來以供參考。設計
一般,咱們使用ToolTip
最簡單的方式是這樣:code
<TextBlock Text="Test" ToolTipService.ToolTip="Test" />
這樣在光標懸浮在TextBlock
上方時,會顯示一個提示條,可是這彷佛又違背了一個設計原則:xml
ToolTip做爲提示,應該僅在當前內容顯示不全,且用戶有意願查看完整內容時做爲替代元素出現對象
這很好理解,若是TextBlock
足以顯示全部文本內容,那麼顯示Tooltip
顯然是畫蛇添足的事情。但UWP並無對這種常見的狀況進行自動處理,好比將TextBlock
在文本溢出時自動顯示Tooltip
做爲一個默認行爲,因此咱們就須要本身來實現這個操做。ip
我能想到的思路是藉助TextBlock.IsTextTrimmed
屬性,在True
的時候設置Tooltip的值爲TextBlock.Text
,在False
的時候設置Tooltip
的值爲null
。get
但在實際建立的時候,我發現這很難作到,緣由以下:string
ConverterParameter
屬性是一個簡單對象(object),沒法經過綁定進行傳值(只有DependencyProperty
才能使用綁定),這意味着我沒法在綁定IsTextTrimmed
的同時經過ConverterParameter
屬性傳入Text的值TextBlock
自己,目標太大,而我只想要IsTextTrimmed
屬性改變時進行判斷.綜上,在查找一些資料後,我決定改造一下Converter
自己。io
Converterclass
public class TrimConverter : DependencyObject, IValueConverter { public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(TrimConverter), new PropertyMetadata("")); public object Convert(object value, Type targetType, object parameter, string language) { bool isTrim = System.Convert.ToBoolean(value); return isTrim ? Text : null; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } }
我在Converter內部建立了一個DependencyProperty
用來存放TextBlock.Text
的值。object
使用
<Page.Resources> <local:TrimConverter x:Key="TrimConverter" Text="{Binding ElementName=TestBlock,Path=Text}"/> </Page.Resources> ... <TextBlock MaxWidth="100" TextTrimming="CharacterEllipsis" x:Name="TestBlock" ToolTipService.ToolTip="{Binding ElementName=TestBlock, Path=IsTextTrimmed, Converter={StaticResource TrimConverter}}"/>
在XAML界面中完成綁定後,實測能夠解決個人需求。
可是這個解決方法並不完美,它有一個問題:
和TextBlock自己耦合,因爲Text值須要綁定,只能一個TextBlock建立一個Converter,不可以複用
實現在TextBlock文本溢出時顯示Tooltip有多種實現方式,我只提出了一種,以供參考。