Search code examples
wpfxamldatagrid

How to define different tooltips for each DataGridCell?


Consider the following DataGrid:

<DataGrid 
    ItemsSource="{Binding People}" 
    AutoGenerateColumns="False" 
>
    <DataGrid.Columns>
        <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
        <DataGridTextColumn Header="Last Name"  Binding="{Binding LastName}"/>
        <DataGridTextColumn Header="Age"        Binding="{Binding Age}"/>
    </DataGrid.Columns>
    
    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}}"/>
        </Style>
    </DataGrid.CellStyle>
</DataGrid>

My intention was to have the content of each cell also appear as tool tip. This
suggests adding the Style to DataGridTextColumn.CellStyle instead of DataGrid.CellStyle, but that would result in a lot of redundant code.

The code above causes the following exception: "Cyclic reference found while evaluating the Style property on element 'System.Windows.Controls.DataGridCell: ...'.

Is there a way of achieving this?


Solution

  • You nearly got it right. The missing piece of the puzzle is what you're binding to from the cell. It's the text property of the content. The content being a TextBlock. There may be some complications here with cell edit template of combobox, checkboxes etc. But you just have datagridtextcolumn there.

     <DataGrid.CellStyle>
          <Style TargetType="DataGridCell">
              <Setter Property="ToolTip" Value="{Binding Path=Content.Text, RelativeSource={RelativeSource Self}}"/>
          </Style>
     </DataGrid.CellStyle>
    

    In the screenshot below I'm using a sample datagrid I happen to have and examining content using snoop. I've selected the content of a datagridcell in the view so we can see what that's made up of in snoop.

    enter image description here

    Not directly related to your question but if you've not examined ui in this way before then notice the parent of any cell is a datagridrow. Whilst we define datagridtextcolumn in xaml what we get is datagridrows rather than a collection of datagrid columns.