Search code examples
c#wpfdatagridtooltip

Adding Tooltip to DataGrid Cells programmatically


i made different approaches to add tooltips to the cells of a DataGrid. I also found several information on this site, but i didn't make it work.

Here's what's the matter and what I've tried:

I have a DataGrid like:

DataGrid grid = new DataGrid();
Binding b = new Binding() { Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.Default, Source = AnObersableCollection, NotifyOnSourceUpdated = true, Path = new PropertyPath(".") } );

grid.SetBinding(DataGrid.ItemsSourceProperty, b);

I'd like that every cell has a tooltip with the cell content as tooltip content, so that truncated text is seen in the tooltip. So i took the CellStyles and created one like this:

Style CellStyle_ToolTip = new Style();
CellStyle_ToolTip.Setters.Add(new Setter(DataGridCell.ToolTipProperty, new ToolTip() { Content = "Yeah!" } ));

That works for static ToolTip contents, but how can I achieve that the ToolTip has the displayed cell content as content?

I found out that

CellStyle_ToolTip.Setters.Add(new Setter(DataGridCell.ToolTipProperty, new ToolTip().SetBinding(ToolTip.ContentProperty, b) ));

does not work and produces an "Cannot set expression. It is marked as "NonShareable" and has already been used"-Error, which makes quite sense as the Binding is already in use. I came to this approach (which probably was complete nonsense) through several other discussions that all use xaml, which is not an option for me. I also found the following solution but don't know how to use without xaml.

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

PS: All columns are DataGridTextColumns, except for one DataGridComboBoxColumn.


Solution

  • Using the CellStyle Property you could do:

    Style CellStyle_ToolTip = new Style();
    var CellSetter = new Setter(DataGridCell.ToolTipProperty, new Binding() {RelativeSource=new RelativeSource(RelativeSourceMode.Self), Path=new PropertyPath("Content.Text")});
    
    CellStyle_ToolTip.Setters.Add(CellSetter); 
    
    grid.CellStyle = CellStyle_ToolTip;