WPF - How to display a tooltip on a hyperlink only

2019-08-04 00:01发布

This is a more specific description of my problem from a previous question, with a follow-up answer.

I had a standard hyperlink defined in XAML:

<TextBlock>
    <Hyperlink IsEnabled="{Binding LinkEnabled}">
        <TextBlock Text="{Binding Text}"/>
    </Hyperlink>
</TextBlock>

The hyperlink's IsEnabled property is bound to a property on the view model, the value of which can change. I needed to place a tooltip on the hyperlink which would only be displayed if the hyperlink is disabled.

1条回答
相关推荐>>
2楼-- · 2019-08-04 00:25

To show the tooltip only when the hyperlink is disabled, the ToolTipService.ShowOnDisabled and ToolTipService.IsEnabled (with the negation converter) properties must be set on the hyperlink:

<TextBlock>
    <Hyperlink IsEnabled="{Binding LinkEnabled}"
               ToolTip="ToolTip"
               ToolTipService.ShowOnDisabled="True"
               ToolTipService.IsEnabled="{Binding IsEnabled, RelativeSource={RelativeSource Self}, Converter={StaticResource negateConverter}}">
        <TextBlock Text="{Binding Text}"/>
    </Hyperlink>
</TextBlock>

However, the tooltip won't be shown, since once the hyperlink is disabled, it stops being hit-testable, because it is contained in the TextBlock (or so I understood).

Thus, the solution would be to change the "IsEnabled" property on the parent TextBlock, not on the hyperlink. However, this works:

<TextBlock IsEnabled="False">

But this doesn't:

<TextBlock IsEnabled="{Binding LinkEnabled}">

In the latter case, changing the TextBlock's IsEnabled property will not change the hyperlink's IsEnabled property. To solve this issue, the hyperlink's IsEnabled property must be bound to the parent's property.

And here is the actual solution, all put together:

<TextBlock IsEnabled="{Binding LinkEnabled}">
    <Hyperlink IsEnabled="{Binding IsEnabled, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type FrameworkElement}}}"
               ToolTip="ToolTip"
               ToolTipService.ShowOnDisabled="True"
               ToolTipService.IsEnabled="{Binding IsEnabled, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type FrameworkElement}}, Converter={StaticResource negateConverter}}">
        <TextBlock Text="{Binding Text}"/>
    </Hyperlink>
</TextBlock>
查看更多
登录 后发表回答