仅在修剪了动态尺寸TextBlock的文本后才显示工具提示吗?

问题描述 投票:0回答:1
<TextBlock x:Name="ContentHeader" Text="{x:bind Name}" ToolTipService.ToolTip="{x:Bind ContentHeader.Text,Mode=OneWay}"
                       ToolTipService.Placement="Right" TextTrimming="CharacterEllipsis"
                       Tapped="ContentHeader_Tapped"  >

条件:我的TextBlock的宽度是根据内容确定的,我没有明确提到任何宽度

c# uwp tooltip uwp-xaml textblock
1个回答
0
投票

此问题的关键是通过TextBlock.IsTextTrimmed属性完成转换。我们可以在Tooltip = null时设置IsTextTrimmed = False,在TextBlock.Text时将工具提示设置为IsTextTrimmed = True

我们不能使用ConverterParameter传递变化的值(TextBlock.Text),因为它是一个简单的对象,而不是DependencyProperty,所以我们需要创建一个可以容纳TextBlock.Text值的转换器。

转换器

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();
    }
}

用法

<Page.Resources>
    <local:TrimConverter x:Key="TrimConverter" Text="{Binding ElementName=TestBlock,Path=Text}"/>
</Page.Resources>

<Grid>
    <TextBlock TextTrimming="CharacterEllipsis"
               x:Name="TestBlock"
               ToolTipService.ToolTip="{Binding ElementName=TestBlock, 
                                                Path=IsTextTrimmed,
                                                Converter={StaticResource TrimConverter}}"/>

</Grid>

这应该可以解决您的问题。

最诚挚的问候。

© www.soinside.com 2019 - 2024. All rights reserved.