Search code examples
wpfdatagridtooltip

Prevent empty tooltips at a wpf datagrid


I am working on a calendar program, which consists mainly of a WPF DataGrid. As there is not always enough space to display all the entries of a day (which is a DataGridCell), a tooltip with all the entries of the day shell appear at mouse over. This works so far with the code snippet shown below. And now the (little) problem: If there are no entries for a day, no tooltip shell pop up. With the code below an empty tooltip pops up.

<DataGridTemplateColumn x:Name="Entry" 
                        IsReadOnly="True">
  <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <Grid>
        <TextBlock Text="{Binding EntryText}"
                   Foreground="{Binding EntryForeground}"
                   FontWeight="{Binding EntryFontWeight}">
        </TextBlock>
        <TextBlock Text="{Binding RightAlignedText}"
                   Foreground="Gray"    
                   Background="Transparent">
          <TextBlock.ToolTip>
            <TextBlock Text="{Binding AllEntriesText}"/>
          </TextBlock.ToolTip>
        </TextBlock>
      </Grid>
    </DataTemplate>
  </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

The Databinding is made via

myCalDataGrid.Itemssource = _listOfDays; 

in code behind, where a 'Day' is the view model for a single calendar row.


Solution

  • As H.B. suggested bind directly to the ToolTip property instead of using TextBlock and in case AllEntriesText is empty string you can apply a trigger on your TextBlock to disable your tooltip by setting the property ToolTipService.IsEnabled like this -

    <TextBlock Text="{Binding RightAlignedText}"
               Foreground="Gray"    
               Background="Transparent"
               ToolTip="{Binding AllEntriesText}">
       <TextBlock.Style>
          <Style TargetType="TextBlock">
             <Style.Triggers>
                <Trigger Property="ToolTip"
                         Value="{x:Static system:String.Empty}">
                   <Setter Property="ToolTipService.IsEnabled" Value="False" />
                </Trigger>
             </Style.Triggers>
           </Style>
        </TextBlock.Style>
    </TextBlock>
    

    Make sure to add namespace system in your xaml -

    xmlns:system="clr-namespace:System;assembly=mscorlib"