我在 Windows 7 上使用 Visual Studio 2012。我需要知道为什么 Grid 所选行的以下样式不适用于背景和前景色,但对于其他属性(例如 BorderBrush 和 BorderThickness 等)却完全适用?虽然我可以看到它们在鼠标悬停在网格行上时发生变化。
<Style x:Key="gridRowStyle" TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="PeachPuff"/>
<Setter Property="Foreground" Value="BlueViolet"/>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="PeachPuff"/>
<Setter Property="Foreground" Value="BlueViolet"/>
<Setter Property="BorderBrush" Value="BlueViolet" />
<Setter Property="BorderThickness" Value="2" />
</Trigger>
</Style.Triggers>
</Style>
这是我在网格上的使用方式。
<DataGrid RowStyle="{StaticResource gridRowStyle}">
我强调知道“为什么”而不是问题的解决方案,因为如果我使用网格单元格样式而不是如下所示的行样式,我已经有了问题的解决方案:
<Style x:Key="gridCellStyle" TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="PeachPuff"/>
<Setter Property="Foreground" Value="BlueViolet"/>
</Trigger>
</Style.Triggers>
</Style>
最佳答案
在具有以下默认样式触发器的 DataGridCell 的默认样式中。
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
<Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
</Trigger>
因此,如果您为 DataGridRow 编写触发器,那么它只会应用于可视化树中放置在 DataGridCell 之前的元素。
因此,要在选择时更改背景和前景,您必须以 DataGridCell 样式编写触发器或从样式中删除默认触发器。
关于所选行的WPF DataGrid RowStyle不改变背景和前景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14876223/