Skip to main content
Home Forums Silverlight Programming Silverlight Controls and Silverlight Toolkit How to set background color of DataGrid rows?
3 replies. Latest Post by yifung on May 27, 2009.
(0)
dandanclick
Member
0 points
16 Posts
05-25-2009 2:17 AM |
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
Participant
876 points
214 Posts
05-26-2009 3:49 AM |
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); } }
Brian Br...
368 points
66 Posts
05-27-2009 4:30 PM |
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
Contributor
3315 points
541 Posts
05-27-2009 8:59 PM |
You can also use e.Row.GetIndex() within the LoadingRow method as Brian suggested above