c# - how to change the background color of the datagrid


Keywords:c# 


Question: 

how do i changing the color of my datagrid i have the color i wan't in the designer but when i debuging it it just changing back to default white i had tryed with this

                <DataGrid.Resources>
                    <Style TargetType="{x:Type DataGrid}">
                        <Setter Property="Background" Value="#FF303030"/>
                    </Style>
                </DataGrid.Resources>

but that didn't worked


1 Answer: 

You need to just define the background color once. If you're also setting it in the DataGrid declaration it will override the style.

e.g. in this first example I'm explicitly setting the background to red in the declaration, so it ignores the color in the style. Result = red background

    <DataGrid Background="Red">
        <DataGrid.Resources>
            <Style TargetType="{x:Type DataGrid}">
                <Setter Property="Background" Value="Green"/>
            </Style>
        </DataGrid.Resources>
    </DataGrid>

Whereas if I remove the color from the declaration it will pick up the color from the style. In this second example you will see a green background.

    <DataGrid>
        <DataGrid.Resources>
            <Style TargetType="{x:Type DataGrid}">
                <Setter Property="Background" Value="Green"/>
            </Style>
        </DataGrid.Resources>
    </DataGrid>

Note that the Background for the DataGrid is the color behind the cells (you might not even see it if your DataGrid is full of data). You might also want to set styles for DataGridRow, DataGridRowHeader and DataGridColumnHeader if you want to change those colors. I've also included the style to set the top-left corner select all button which is a little trickier, taken from Style datagrid table - Top left corner

    <DataGrid>
        <DataGrid.Resources>
            <Style TargetType="{x:Type DataGrid}">
                <Setter Property="Background" Value="Green"/>
            </Style>
            <Style TargetType="{x:Type DataGridRow}">
                <Setter Property="Background" Value="Blue"/>
            </Style>
            <Style TargetType="{x:Type DataGridRowHeader}">
                <Setter Property="Background" Value="Yellow"/>
            </Style>
            <Style TargetType="{x:Type DataGridColumnHeader}">
                <Setter Property="Background" Value="Orange"/>
            </Style>
            <Style TargetType="{x:Type Button}" x:Key="{ComponentResourceKey ResourceId=DataGridSelectAllButtonStyle, TypeInTargetAssembly={x:Type DataGrid}}">
                <Setter Property="Background" Value="Black" />
            </Style>
        </DataGrid.Resources>
    </DataGrid>