以编程方式将工具提示添加到 DataGrid 单元格

Adding Tooltip to DataGrid Cells programmatically

我采用不同的方法将工具提示添加到 DataGrid 的单元格。我也在这个网站上找到了一些信息,但我没有让它起作用。

这是问题所在以及我尝试过的方法:

我有一个像这样的 DataGrid:

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);

我希望每个单元格都有一个工具提示,将单元格内容作为工具提示内容,以便在工具提示中看到截断的文本。所以我采用了 CellStyles 并创建了一个这样的:

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

这适用于静态工具提示内容,但如何实现工具提示将显示的单元格内容作为内容?

我发现

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

不起作用并产生“无法设置表达式。它被标记为“不可共享”并且已被使用”-错误​​,这很有意义,因为绑定已在使用中。我通过其他几个都使用 xaml 的讨论得出了这种方法(这可能完全是胡说八道),这对我来说不是一个选择。我还找到了以下解决方案,但不知道如何在没有 xaml.

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

PS:所有列都是DataGridTextColumns,一个DataGridComboBoxColumn除外。

使用 CellStyle 属性 你可以:

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;