首页 > 解决方案 > DataGridTextColumn 工具提示问题

问题描述

我有这种风格来向数据网格的每一行中的单元格添加工具提示。问题是所有工具提示都具有相同的文本(第一行的文本)。我究竟做错了什么?

        <DataGridTextColumn Header="Profit (%)"
                            Binding="{Binding Percentage, StringFormat=N8}">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="{x:Type DataGridCell}"
                       BasedOn="{StaticResource {x:Type DataGridCell}}">
                    <Setter Property="ToolTip">
                        <Setter.Value>
                            <ToolTip>
                                <ToolTip.ContentTemplate>
                                    <DataTemplate>
                                        <TextBlock Text="{Binding Content.Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridCell}}}" />
                                    </DataTemplate>
                                </ToolTip.ContentTemplate>
                            </ToolTip>
                        </Setter.Value>
                    </Setter>
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>

但是如果我使用一个简单的工具提示,它就完美了

<DataGridTextColumn Header="Profit (%)"
                    Binding="{Binding Percentage, StringFormat=N8}">
    <DataGridTextColumn.CellStyle>
        <Style TargetType="{x:Type DataGridCell}"
               BasedOn="{StaticResource {x:Type DataGridCell}}">
            <Setter Property="ToolTip"
                    Value="{Binding Percentage}" />
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>

标签: wpfxaml

解决方案


摆脱ContentTemplate并将其设置为Tooltip绑定TextBlock到父级的 a DataGridCell

<DataGridTextColumn.CellStyle>
    <Style TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource {x:Type DataGridCell}}">
        <Setter Property="ToolTip">
            <Setter.Value>
                <ToolTip>
                    <TextBlock Text="{Binding PlacementTarget.Content.Text, 
                            RelativeSource={RelativeSource AncestorType=ToolTip}}" />
                </ToolTip>
            </Setter.Value>
        </Setter>
    </Style>
</DataGridTextColumn.CellStyle>

推荐阅读