如果需要显示工具提示WPF [英] Show WPF Tooltip if needed
问题描述
我有一个有限的尺寸内控制一个TextBlock。如果文本太长而不能在控制,我想显示全文提示。这是一个典型的行为从许多应用程序一定会知道。
I have a TextBlock inside a limited-size control. If the text is too long to fit into the control, I'd like to show a tooltip with full text. This is a classic behavior you surely know from many apps.
我试着使用转换器转换成TextBlock的宽度为工具提示的可见性。
I tried using a Converter to convert TextBlock width into Tooltip's Visibility.
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text}">
<TextBlock.ToolTip>
<ToolTip
DataContext="{TemplateBinding Content}"
Visibility="{Binding Converter={StaticResource visConvert}}">
<TextBlock Text="{Binding Text}"></TextBlock>
</ToolTip>
</TextBlock.ToolTip>
</TextBlock>
</DataTemplate>
</GridViewColumn.CellTemplate>
的问题是,在转换器:
The problem is that in the Converter:
public object Convert(object value, ...
价值是数据绑定的项目。我想的'价值'是TextBlock的,要注意观察它的宽度,其比作GridViewColumn.Width。
'value' is the DataBound item. I'd like the 'value' to be the TextBlock, to observe its Width, and compare it to the GridViewColumn.Width.
推荐答案
我想通了,说明文字的 PlacementTarget 属性,指定具有工具提示的UI元素万一有人需要它:
I figured it out, the Tooltip has PlacementTarget property that specifies the UI element that has the Tooltip. In case anyone needs it:
<TextBlock Text="{Binding Text}">
<TextBlock.ToolTip>
<ToolTip
DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}"
Visibility="{Binding Converter={StaticResource toolVisConverter}}">
<TextBlock Text="{Binding Text}"/> <!-- tooltip content -->
</ToolTip>
</TextBlock.ToolTip>
</TextBlock>
然后编写转换的TextBlock能见度一个转换器(基于TextBlock的宽度)。
And then write a Converter that converts TextBlock to Visibility (based on TextBlock width).
这篇关于如果需要显示工具提示WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!