问题
Setting background works fine for DataGridCheckBoxColumn
but not for DataGridTextColumn
. I set it for cell in resources:
<Style TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="#ffff00" />
</Trigger>
<Trigger Property="IsEditing" Value="True">
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="#00ff00" />
<Setter Property="Background" Value="#00ff00" />
</Trigger>
</Style.Triggers>
</Style>
Is there any solution for this issue?
回答1:
You should add magic
string:
<SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="Transparent" />
in your resources, for example in <Window.Resources>
.
In this case, when IsEditing="True"
color is assigned by default (White
), which is taken from the SystemColors. But then you need to explicitly set the color for the main panel or for Window
.
Or set this string in <DataGrid.Resources>
with Background="White"
:
<DataGrid Background="White" ...>
<DataGrid.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="Transparent" />
</DataGrid.Resources>
...
</DataGrid>
回答2:
The accepted answer is great until it causes side-effects. In my case, it was causing the editing caret to be invisible when editing, probably because setting the "magic" system color was messing with the logic that sets the caret color automatically.
A better solution is to simply override the style that the grid uses when it's in edit mode (the DataGridTextColumn.EditingElementStyle
), like this:
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn>
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="TextBox">
<Setter Property="Background" Value="#00ff00"/>
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
Yet another solution is to make your own DataGridTemplateColumn
, as shown here. This gives you full control over your column, instead of fighting against whatever the built-in DataGridTextColumn
wants to do. This, however, may be too much power, as it may force you to deal with details you may not want to. But FWIW, it's what worked in my case.
来源:https://stackoverflow.com/questions/21827661/how-to-change-background-of-datagridcell-when-isediting-true-in-wpf