Binding DataGridCell ToolTip property to value of DataGridCell

monstr picture monstr · Dec 11, 2014 · Viewed 10.9k times · Source

I have DataGrid and one of the DataGrid columns looks like this

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

The problem is I forced to use BooleanToYesNoConverter converter twice. It means that Convert method of BooleanToYesNoConverter will be invoked twice. Therefore, I want to optimize my code. And want to bind value of ToolTip property directly to value of cell.

I tried approach with using ElementName-s. But I have no idea what should I specify in Path property of binding.

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

I tried to use DataGridTemplateColumn instead of DataGridTextColumn, but it does't work too.

<DataGridTemplateColumn CanUserSort="False"
                        Header="Значение"
                        Width="*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Value, Converter={StaticResource BooleanToYesNoConverter}}"
                        Name="_textBlock"/>    
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="ToolTip" Value="{Binding RelativeSource ElementName=_textBlock, Path=Text}" />
        </Style>
    </DataGridTemplateColumn.CellStyle>
</DataGridTemplateColumn>

How can I solve my task. Is it possible at all?

Answer

Amol Bavannavar picture Amol Bavannavar · Dec 11, 2014

Use this Style :

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