将DataGridCell ToolTip属性绑定到DataGridCell的值

mon*_*str 8 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>
Run Code Online (Sandbox Code Playgroud)

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

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

<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>
Run Code Online (Sandbox Code Playgroud)

我尝试使用DataGridTemplateColumn而不是DataGridTextColumn,但它也不起作用.

<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>
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决我的任务.有可能吗?

Amo*_*var 19

使用此样式:

<Style TargetType="DataGridCell">
    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=Content.Text}"/>
 </Style>
Run Code Online (Sandbox Code Playgroud)

  • 如果您只想将工具提示应用到网格的特定列,则 (1) 为样式添加一个键,例如``&lt;Style x:Key="CellWithTooltip" ...&gt;`` 并 (2) 应用它到像这样``&lt;DataGridTextColumn CellStyle="{StaticResource CellWithTooltip}" ... /&gt;``这样的想要的列。 (2认同)