4thSpace 4thSpace - 3 months ago 37
C# Question

How to stop DataGrid row color from changing?

I've implemented code to get around the double click issue when selecting a row in a WPF DataGrid. I'm using the following code from here: http://stackoverflow.com/a/5857908/40106.

<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="IsEditing" Value="True" />
</Trigger>
</Style.Triggers>
</Style>


Rows have alternating colors. The problem is when I mouse over a row, in one column, the light blue color is replaced by white.

The above code works great except for this one issue. How do I stop the color from changing when mousing over a row?

I have tried the following but it doesn't have any effect:

<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="IsEditing" Value="True" />
<Setter Property="Background" Value"AliceBlue" />
</Trigger>
</Style.Triggers>
</Style>

Answer

The problem is, that the cell will display it's edit style when you hover the mouse above the cell.

For a DataGridTextColumn this means, that a TextBox with a white background is displayed.

You can set a Style to <DataGridTextColumn.EditingElementStyle> and set the Background to transparent.

<DataGridTextColumn Header="Name" Binding="{Binding Name}" >
    <DataGridTextColumn.EditingElementStyle>
        <Style TargetType="TextBox">
            <Setter Property="Background" Value="Transparent"></Setter>
            <Setter Property="BorderThickness" Value="0"></Setter>
        </Style>
    </DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>

To get the white Background, when actually editing the cell you could add another trigger to the IsSelected event:

<Style TargetType="DataGridCell">
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="IsEditing" Value="True" />
        </Trigger>

        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="White"/>
        </Trigger>

    </Style.Triggers>
</Style>

Another option would be to apply the DataGridCell Style to CheckBoxColumns only. For other Column types it wouldn't make a difference anyway.