以下是如何在选择单元格时设置背景的示例,但是当我实际单击单元格内部进行编辑时,颜色会发生变化。在编辑单元格时是否有触发器属性?我希望背景不要改变。
<DataGrid Name="DG1" ItemsSource="{Binding}" SelectionUnit="Cell" >
<DataGrid.CellStyle>
<Style TargetType="DataGridCell" >
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="SeaGreen"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>
回答我自己的问题,看起来Cell背景颜色基于SystemColors.WindowBrushKey
。覆盖像<SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="Red" />
这样的资源就可以了。
`
答案 0 :(得分:9)
您可以为IsEditing
状态的现有样式添加另一个触发器。然后,您可以为触发器内的ControlTemplate
设置DataGridCell
。
<Trigger Property="IsEditing" Value="True">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridCell">
<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text, Mode=TwoWay, UpdateSourceTrigger=Default}"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Padding="0" BorderThickness="0" Background="SeaGreen"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
答案 1 :(得分:0)
这适用于DataGridTemplateColumn以及其他类型,例如DataGridTextColumn,DataGridCheckboxColumn等:
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Padding" Value="0" />
<Setter Property="Margin" Value="0" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border x:Name="CellBorder"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
SnapsToDevicePixels="True">
<ContentPresenter HorizontalAlignment="Stretch" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEditing" Value="True">
<Setter TargetName="CellBorder" Property="BorderBrush" Value="Green" />
<Setter TargetName="CellBorder" Property="Background" Value="yellow" />
<Setter TargetName="CellBorder" Property="BorderThickness" Value="1" />
<Setter Property="Foreground" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>