如何修改WPF中DataGrid选中项的背景色?触发器失效求助
问题原因及解决方法
你的触发器不生效有两个核心问题:
- 错误地将
DataGridCell.IsSelected触发器放在了DataGrid的Style中,而DataGrid本身并不具备这个属性,触发器无法触发。 - WPF默认的
DataGridCell选中样式优先级较高,会覆盖你设置的Background属性。
修正后的代码
<DataGrid x:Name="dgAdatok" ColumnWidth="*" MinColumnWidth="100" FontSize="9.5" Background="Transparent" Grid.RowSpan="4" BorderThickness="0" Margin="0,30,0,0" > <DataGrid.Resources> <Style TargetType="DataGridColumnHeader"> <Setter Property="Background" Value="Purple"/> <Setter Property="Foreground" Value="White"/> </Style> <Style TargetType="DataGridCell"> <Setter Property="Background" Value="#DA34AE"/> <Setter Property="Foreground" Value="Black"/> <Setter Property="BorderBrush" Value="#DA34AE"/> <!-- 为单元格添加选中状态触发器 --> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="Blue"/> <Setter Property="Foreground" Value="White"/> <Setter Property="BorderBrush" Value="DarkBlue"/> </Trigger> </Style.Triggers> <!-- 覆盖默认模板,确保自定义样式优先级生效 --> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type DataGridCell}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True"> <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </DataGrid.Resources> </DataGrid>
关键修改点
- 将
IsSelected触发器移至DataGridCell的Style内,因为选中状态是单元格的属性,而非DataGrid的全局属性。 - 覆盖
DataGridCell的默认模板,避免WPF内置的选中样式覆盖你的自定义设置。
内容的提问来源于stack exchange,提问作者yvessaintlaurent
相关产品推荐
相关产品推荐

