Show WPF Tooltip if needed

前端 未结 3 666
粉色の甜心
粉色の甜心 2020-12-13 07:12

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

相关标签:
3条回答
  • 2020-12-13 07:28

    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>
    

    And then write a Converter that converts TextBlock to Visibility (based on TextBlock width).

    0 讨论(0)
  • 2020-12-13 07:30

    Ok, so why do it the hard XAML-only way? This works:

    <TextBlock Text="{Binding Text}"
         IsMouseDirectlyOverChanged="TextBlock_IsMouseDirectlyOverChanged" >
         <TextBlock.ToolTip>
         <ToolTip Visibility="Collapsed">
             <TextBlock Text="{Binding Text}"></TextBlock>
         </ToolTip>
         </TextBlock.ToolTip>
    </TextBlock>
    

    in Control.xaml.cs:

    private void TextBlock_IsMouseDirectlyOverChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        bool isMouseOver = (bool)e.NewValue;
        if (!isMouseOver)
            return;
        TextBlock textBlock = (TextBlock)sender;
        bool needed = textBlock.ActualWidth > 
            (this.listView.View as GridView).Columns[2].ActualWidth;
        ((ToolTip)textBlock.ToolTip).Visibility = 
            needed ? Visibility.Visible : Visibility.Collapsed;
    }
    
    0 讨论(0)
  • 2020-12-13 07:43

    I would think you have to look at a ControlTemplate trigger to solve this problem. Unfortunately ControlTemplate triggers always compare with a specific value, not less than or greater than. You can make it appear e.g. if the Width = 100, not Width < 100.

    0 讨论(0)
提交回复
热议问题