Skip to main content

Microsoft Silverlight

Answered Question How to set background color of DataGrid rows?RSS Feed

(0)

dandanclick
dandanclick

Member

Member

0 points

16 Posts

How to set background color of DataGrid rows?

Hi,

I have datagrid with 6 rows. I want color the rows with some colors: I want add red color to lines 1,6 & add blue color to lines 2,5 & add yellow color to lines 3,4.

 Thanks!

meykih
meykih

Participant

Participant

876 points

214 Posts

Re: How to set background color of DataGrid rows?

You want to set the background of some rows with known numbers to specific color? Use the LoadingRow-Event and a counter that can tell you which row is loaded:

 
private int counter =0;
private void LoadGridRow(object sender, DataGridRowEventArgs e)
{
    counter++;

    if(counter==1)
    {
        e.Row.Background = Color.FromArgb(255,255,0,0);
    }
}
and so one for the other lines and colors

Regards,
Maike Ohlig

Please mark post as answer if it helped you

Brian Braeckel
Brian Br...

Member

Member

368 points

66 Posts

Answered Question

Re: How to set background color of DataGrid rows?

Don't rely on a counter to associate a row with an index, it won't work when you scroll around or sort.  Use the row's DataContext to see what item has just been loaded, and set the color according to that item's index.  Also, it's important that you undo any changes you make to a row inside of LoadingRow inside of the UnloadingRow event.  The rows are recycled; if you don't clean them up correctly when they unload you'll see some funny behavior.  For example:


void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    int index = myList.IndexOf(e.Row.DataContext);
    if (index == 5)
    {
        e.Row.Background = new SolidColorBrush(Colors.Purple);
    }
}

void dataGrid_UnloadingRow(object sender, DataGridRowEventArgs e)
{
    e.Row.Background = null;
}

Another option is to databind the row's Background to a property inside your data object, or use a custom value converter to convert one of your existing properties into a color.

yifung
yifung

Contributor

Contributor

3315 points

541 Posts

Microsoft
Answered Question

Re: How to set background color of DataGrid rows?

You can also use e.Row.GetIndex() within the LoadingRow method as Brian suggested above

Yifung Lin [MSFT]
  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities