如何为每个 DataGridCell 定义不同的工具提示?
How to define different tooltips for each DataGridCell?
考虑以下数据网格:
<DataGrid
ItemsSource="{Binding People}"
AutoGenerateColumns="False"
>
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/>
<DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
</DataGrid.Columns>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}}"/>
</Style>
</DataGrid.CellStyle>
</DataGrid>
我的意图是让每个单元格的内容也显示为工具提示。 This
建议将 Style
添加到 DataGridTextColumn.CellStyle
而不是 DataGrid.CellStyle
,但这会导致大量冗余代码。
上面的代码导致以下异常:“在评估元素 'System.Windows.Controls.DataGridCell: ...' 上的样式 属性 时发现循环引用。
有办法实现吗?
你几乎做对了。
缺少的一块拼图是您要从单元格绑定到什么。
它是内容的文本属性。内容是一个 TextBlock。
组合框、复选框等的单元格编辑模板可能会有些复杂。
但是你那里只有 datagridtextcolumn。
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="ToolTip" Value="{Binding Path=Content.Text, RelativeSource={RelativeSource Self}}"/>
</Style>
</DataGrid.CellStyle>
在下面的屏幕截图中,我使用的是我碰巧拥有的示例数据网格,并使用 snoop 检查内容。我在视图中选择了一个数据网格单元格的内容,这样我们就可以在 snoop 中看到它是由什么组成的。
与您的问题没有直接关系,但如果您之前没有以这种方式检查过 ui,请注意任何单元格的父级都是数据网格行。虽然我们在 xaml 中定义了 datagridtextcolumn,但我们得到的是 datagridrows 而不是 datagrid 列的集合。
考虑以下数据网格:
<DataGrid
ItemsSource="{Binding People}"
AutoGenerateColumns="False"
>
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/>
<DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
</DataGrid.Columns>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}}"/>
</Style>
</DataGrid.CellStyle>
</DataGrid>
我的意图是让每个单元格的内容也显示为工具提示。 This
建议将 Style
添加到 DataGridTextColumn.CellStyle
而不是 DataGrid.CellStyle
,但这会导致大量冗余代码。
上面的代码导致以下异常:“在评估元素 'System.Windows.Controls.DataGridCell: ...' 上的样式 属性 时发现循环引用。
有办法实现吗?
你几乎做对了。 缺少的一块拼图是您要从单元格绑定到什么。 它是内容的文本属性。内容是一个 TextBlock。 组合框、复选框等的单元格编辑模板可能会有些复杂。 但是你那里只有 datagridtextcolumn。
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="ToolTip" Value="{Binding Path=Content.Text, RelativeSource={RelativeSource Self}}"/>
</Style>
</DataGrid.CellStyle>
在下面的屏幕截图中,我使用的是我碰巧拥有的示例数据网格,并使用 snoop 检查内容。我在视图中选择了一个数据网格单元格的内容,这样我们就可以在 snoop 中看到它是由什么组成的。
与您的问题没有直接关系,但如果您之前没有以这种方式检查过 ui,请注意任何单元格的父级都是数据网格行。虽然我们在 xaml 中定义了 datagridtextcolumn,但我们得到的是 datagridrows 而不是 datagrid 列的集合。