Changing the color of alternate listbox item.
-
Monday, September 20, 2010 11:51 AM
Hi,
I have created a Listbox with a data template. I want to change the background color of every alternate listbox item.
Please let me know how to do this?
All Replies
-
Monday, September 20, 2010 12:06 PMYou may be able to bind the listbox item's background colour to some kind of code that chooses one colour for all the odd numbered items (using the list/array/collection index) and another for even numbered ones.
My WIP Windows Phone 7 App - London Travel http://www.mdtadesign.co.uk/windows-phone-7-app-london-travel/ -
Monday, September 20, 2010 1:12 PM
Here's some code using a value convertor...
public class AlternatingRowsConverter : IValueConverter { private bool _alternate; public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { _alternate = !_alternate; return _alternate ? new SolidColorBrush(Color.FromArgb(255, 255, 0, 0)) : new SolidColorBrush(Color.FromArgb(255, 0, 0, 255)); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
Then, listbox template:
<ListBox ItemsSource="{Binding}" x:Name="Mylistbox" SelectionChanged="Mylistbox_SelectionChanged"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <Grid Background="{Binding Converter={StaticResource alternateConvertor}}"> <TextBlock Grid.Column="0" Text="{Binding Name, Mode=TwoWay}" VerticalAlignment="Center" HorizontalAlignment="Left" /> </Grid> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>and finally define the convertor object in the resource dictionary:
Probably the converter shouldn't rely on the call sequence but should retrieve the list index but this should get you started.<phone:PhoneApplicationPage.Resources> <WindowsPhoneApplication5:AlternatingRowsConverter x:Key="alternateConvertor" /> </phone:PhoneApplicationPage.Resources>
http://babaandthepigman.spaces.live.com/blog/- Proposed As Answer by James E. Ashley Monday, September 20, 2010 1:41 PM