【UWP】僅在TextBlock文本溢出時顯示Tooltip

前言

這是我今天在回答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的值爲nullget

但在實際建立的時候,我發現這很難作到,緣由以下:string

  1. Converter的ConverterParameter屬性是一個簡單對象(object),沒法經過綁定進行傳值(只有DependencyProperty才能使用綁定),這意味着我沒法在綁定IsTextTrimmed的同時經過ConverterParameter屬性傳入Text的值
  2. 我也不能直接在Converter內綁定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有多種實現方式,我只提出了一種,以供參考。

相關文章
相關標籤/搜索