将DataGridCell ToolTip属性绑定到DataGridCell的值

时间:2014-12-11 08:31:48

标签: c# wpf tooltip datagridcell

我有DataGrid,其中一个DataGrid列看起来像这样

<DataGridTextColumn Header="Value" 
        Binding="{Binding Value, Converter={StaticResource BooleanToYesNoConverter}}" 
        x:Name="_col2" 
        IsReadOnly="True"
        CanUserSort="False"
        Width="*">
    <DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="ToolTip" Value="{Binding Value, Converter={StaticResource BooleanToYesNoConverter}}" />
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>

问题是我被迫两次使用BooleanToYesNoConverter转换器。这意味着Convert的{​​{1}}方法将被调用两次。因此,我想优化我的代码。并希望将BooleanToYesNoConverter属性的值直接绑定到单元格的值。

我尝试使用ToolTip - s。但我不知道我应该在绑定的 Path 属性中指定什么。

ElementName

我尝试使用<DataGridTextColumn Header="Value" Binding="{Binding Value, Converter={StaticResource BooleanToYesNoConverter}}" x:Name="_col2" IsReadOnly="True" CanUserSort="False" Width="*"> <DataGridTextColumn.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="ToolTip" Value="{Binding ElementName=_col2, Path=???}" /> </Style> </DataGridTextColumn.CellStyle> </DataGridTextColumn> 代替DataGridTemplateColumn,但它也不起作用。

DataGridTextColumn

我该如何解决我的任务。它有可能吗?

2 个答案:

答案 0 :(得分:18)

使用此样式:

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

答案 1 :(得分:0)

尝试将ToolTip设置为DataGridCell的DataContext,如下所示:

<DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="ToolTip" Value="{Binding}" />
        </Style>
</DataGridTextColumn.CellStyle>

如果您没有获得所需的内容,则可以指定转换器:

<DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="ToolTip" Value="{Binding Converter={StaticResource BooleanToYesNoConverter}}" />
        </Style>
</DataGridTextColumn.CellStyle>