0
votes

I want to have alternating background colors of a listbox in my MVVM Light WP7 project.

WP7 has no support for alternating the background color of the ListBox items background.

I have a listbox that has its itemsource set to a CollectionViewSource. The CollectionViewSource is in turn bound to an ObservableCollection in my ViewModel. The CollectionViewSource is configured to sort the list by a datetime property in my custom object.

When the list is scrolled to the bottom a command is sent to the viewmodel to add more data to my collection. Since the CollectionViewSource sort on the datetime the items can appear anywhere in the list, not just at the end.

This makes approches like http://chillijam.co.uk/2012/01/11/alternating-listbox-item-background-colours-in-wp7/ and How to apply alternate row style in listbox in window phone 7 not work. Since they only check the previously added item.

I have also subscribed to the ListView UpdateLayout event and there go through each element in the ListBox and alternate the background, but this triggers to many times and made the app really unresponsive.

Does anyone have an idea?

1
This soulution works well the first time the data is loaded. But when i add items to the list, the list is reordered, but the alternating colors come out wrong. - Mårten Palm
I saw a note about that which is why I just posted the link as a comment. - ChrisF
Yes, that solution was the first I tried. But my question is still unanswered. The posts that are refered to does not work in this case. - Mårten Palm

1 Answers

1
votes

You can try accessing rows by their number and add colors to them like.

if( row.id % 2 ==0)
//first color
else 
//second color

EDIT: I used this to modify listbox row background when it's selected

     ListBoxItem lbiSelected = (ListBoxItem)(CalcultionList.ItemContainerGenerator.ContainerFromIndex(selectedItemIndex));
     //CalculationList is the name of my listbox
     lbiSelected.Background = new SolidColorBrush(Colors.Red);