Friday, February 21, 2014

Hiding empty tooltips

This post is for WPF 4.0

I have a grid whose contents may overflow the size of the cell they are in. The common solution to this is to add a tooltip to the cell that contains the entire contents. The user then floats the mouse over the cell and sees the tooltip. This is easy to achieve. The example below defines a grid column that is bound to the ItemSource's Description property and has a tooltip that lasts one minute to give the slower users a chance to read the full description. Sometimes five seconds just isn't enough :-)

<DataGridTextColumn Width="200" Binding="{Binding Description}">
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource TextBlockDefaultStyle}">
            <Setter Property="ToolTip" Value="{Binding Description}">
            <Setter Property="ToolTipService.ShowDuration" Value="60000"> 
        </Style> 
    </DataGridTextColumn.ElementStyle> 
</DataGridTextColumn> 

The only downside to this is that the user sees an empty tooltip if the content of the cell is empty. I wrote a style in my application's resource dictionary to hide the tooltip if the content is empty. Notice the definition of the sys namespace which is needed to define an empty string in XAML.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <Style TargetType="{x:Type ToolTip}">
        <Style.Triggers>
            <Trigger Property="Content" Value="{x:Static sys:String.Empty}">
                <Setter Property="Visibility" Value="Collapsed"/>
            </Trigger> 
            <Trigger Property="Content" Value="{x:Null}"> 
                <Setter Property="Visibility" Value="Collapsed"/> 
            </Trigger> 
        </Style.Triggers> 
    </Style> 
</ResourceDictionary>

Now the application will hide all empty tooltips.

4 comments: