Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change the background color of the datagrid

How do I change the color of my DataGrid? If I have the color I want in the designer, when I'm debugging, it just changes back to the default white?

I tried with this:

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

but that didn't work.

like image 332
omini data Avatar asked Dec 19 '25 05:12

omini data


1 Answers

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>
like image 168
Tone Avatar answered Dec 20 '25 20:12

Tone