WPF DataGrid格式化问题:DataGridRow与DataGridCell样式无法同时生效
冲突原因
你重写了DataGridCell的ControlTemplate,默认的DataGridCell模板内置了选中状态的处理逻辑,会自动读取SystemColors.HighlightBrushKey资源作为选中背景。自定义模板时你完全删除了这部分状态触发器,且自定义的Border没有继承选中状态的背景设置,相当于单元格的背景盖住了行层面的高亮背景,因此看不到你定义的黄色高亮。
解决方案
方案1(推荐):无需重写Cell模板,直接设置Padding属性
你要实现单元格内边距完全不需要重写控件模板,直接给DataGridCell加Padding的Setter即可,保留所有默认逻辑,不会和行高亮样式冲突:
<!-- 修改后的DataGridCell样式 --> <Style x:Key="MyCellStyle" TargetType="{x:Type DataGridCell}"> <Setter Property="Padding" Value="15,10,10,15"/> </Style>
修改后原有的MyRowStyle不需要做任何调整,单元格内边距和选中高亮效果可同时生效。
方案2:若必须自定义Cell模板,补充选中状态触发器
如果你有其他自定义需求必须重写DataGridCell的模板,需要手动补充选中状态的触发逻辑:
<Style x:Key="MyCellStyle" TargetType="{x:Type DataGridCell}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type DataGridCell}"> <Border x:Name="border" Padding="15,10,10,15" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ContentPresenter/> </Border> <ControlTemplate.Triggers> <!-- 补充选中状态处理 --> <Trigger Property="IsSelected" Value="True"> <Setter TargetName="border" Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>
内容的提问来源于stack exchange,提问作者ChE Junkie
相关产品推荐
相关产品推荐

