Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you change WPF DataGrid cell background while editing the cell?

Tags:

wpf

datagrid

The following is an example of how to set the background when the cell is selected, but when I actually click inside the cell to edit it the color changes. Is there a trigger property for when a cell is being edited? I'd like the background not to change.

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

Answering my own question, it looks like the Cell background color is based off of SystemColors.WindowBrushKey. Overriding that resource like such <SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="Red" /> did the trick. `

like image 646
Aaron D. Avatar asked Sep 15 '25 00:09

Aaron D.


1 Answers

You can add another trigger into your existing style for the IsEditing state. Then you can set the ControlTemplate for the DataGridCell inside of the trigger.

<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>
like image 115
Mash Avatar answered Sep 17 '25 19:09

Mash