Add custom tooltip to row in DataGrid

2020-08-14 15:37发布

问题:

I would like to customize my DataGrid to show a tooltip within the selected row, please see the mockup images below for a better idea of what I want to achieve.

As it is at the moment - Shows a single selected row:

How I would like - Shows the same row selected, now with tooltip:

  • My DataGrid uses Binding to the ViewModel.
  • Working with WPF & C# for Windows desktop.

I don't really have any idea how to achieve this, so I'm open to any suggestions at all.

回答1:

You can use RowDetailsTemplate.

Here is sample code:

<DataGrid Name="grid" AutoGenerateColumns="False">
    <DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <TextBlock Background="Orange" Text="{Binding MoreInfo}" TextWrapping="Wrap"
                       HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
        </DataTemplate>
    </DataGrid.RowDetailsTemplate>
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding ID}" />
        <DataGridTextColumn Header="ID" Binding="{Binding Name}" />
        <DataGridTextColumn Header="ID" Binding="{Binding Surname}" />
    </DataGrid.Columns>
</DataGrid>


回答2:

I use the DataGrid.RowStyle to set the tooltip.

My bound objects have a ToolTipText property which contains the content of the ToolTip.

<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Setter Property="ToolTip">
            <Setter.Value>
                <TextBlock Text="{Binding ToolTipText}" />
            </Setter.Value>
        </Setter>
    </Style>
</DataGrid.RowStyle>


回答3:

Another simple way to add a tooltip on a row in a datagrid is the following.

Use the LodingRowEvent and add your tooltip like this:

private void grdItemlogs_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        if (e.Row != null)
        {
            string toolTipText = "Your Tooltip string content"
            e.Row.ToolTip = toolTipText;

        }
    }