Click here to Skip to main content
15,878,748 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I just want to to set background of a cell to Red.
I added a rectangle in the cell and change the background to pink.
But I don't why my code does not work.
Any help please?

P.S: Accidentally I changed the Height of rectangle to 10, and I saw there appear a little pink band in the cell !!!! But I couldn't understand what is it!!!!

What I have tried:

<DataGridTemplateColumn Header="MyHeader" IsReadOnly="True" Width="2*">
            <Rectangle Fill="Pink" Height="Auto"/>
Updated 31-Dec-23 23:59pm

Share this answer
Sh.H. 1-Jan-24 6:30am    
Thanks. This example has TextBlock. I do not want to have any element in the cell. Beside, I followed your suggestion and I used TextBlock as the example. There appears just a little triangle at the middle of cell.
Anyway... doesn't work.
Your Rectangle has nothing to use for a "size request" ... at a minimum, give the Rectangle a .MinHeight and a .MinWidth in this case (e.g. 24x24 or 32x32). If the Rectangle was "contained", and "stretched", you wouldn't need to specify dimensions, but there are no other controls in the template.

(I say .Min... because some controls have a default .Min..., and anything less, won't work if specified via .Width or .Height only).
Share this answer
Sh.H. 2-Jan-24 16:41pm    
@Gerry Schmitz
You are right. If I use min or max, it works. But I do not want to show the rectangle as min. I need the rectangle to be stretch. But it doesn't work in the code.
You do not need a Rectangle to set the background color of a cell, you just need to set the Cell Style. Here is a working example:

<Window x:Class="WpfDataGridCellBackground.MainWindow"
        Title="MainWindow" Height="450" Width="800">
        <SolidColorBrush x:Key="clBr" Color="Red" />
        <DataGrid ItemsSource="{Binding Path=.}"
                <DataGridTextColumn Header="First Name" 
                                    Binding="{Binding Path=FirstName}">
                        <Style TargetType="DataGridCell">
                            <Setter Property="Background" 
                                    Value="{StaticResource clBr}" />

                <DataGridTextColumn Header="Last Name" 
                                    Binding="{Binding Path=LastName}">


And the code-behind:
using System.Windows;

namespace WpfDataGridCellBackground;

public partial class MainWindow : Window
    public MainWindow()
        DataContext = new List<Person>()
            new("Freddie", "Mercury"),
            new("John", "Lennon")

public record Person(string FirstName, string LastName);
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900