Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show WPF Tooltip if needed

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.

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, ...

'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.

like image 676
Martin Konicek Avatar asked Jul 12 '09 12:07

Martin Konicek


1 Answers

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;
}
like image 145
Martin Konicek Avatar answered Oct 19 '22 02:10

Martin Konicek