4

以下是选择单元格时如何设置背景的示例,但是当我实际单击单元格内部进行编辑时,颜色会发生变化。编辑单元格时是否有触发属性?我希望背景不要改变。

<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>

回答我自己的问题,看起来单元格背景颜色是基于SystemColors.WindowBrushKey. 像这样覆盖该资源<SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="Red" />就可以了。`

4

2 回答 2

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>
于 2013-02-09T06:35:16.453 回答
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>
于 2018-09-27T13:37:30.143 回答