Alternating row background color for ListBox rows

2019-09-08 05:33发布

问题:

I am trying to give alternate row style in listbox in window phone 7.

I have used the below: It worked if i have few rows.

 <ListBox x:Name="ListBox1" Width="500" Height="300">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Width="500" Background="{Binding age,Converter={StaticResource myconverter}}">
                              <TextBlock Text="Some text"></TextBlock> 
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

and this is my converter which changing the background color:

public class MyConverter : IValueConverter
    {
        bool flag = false;
        SolidColorBrush brush1 = new SolidColorBrush(Color.FromArgb(255, 100, 200, 255));
        SolidColorBrush brush2 = new SolidColorBrush(Color.FromArgb(255, 200, 100, 155));
        public object Convert(object value,
                              Type targetType,
                              object parameter,
                              System.Globalization.CultureInfo culture)
        {

            flag = !flag;
            return flag ? brush1 : brush2;

        }

        public object ConvertBack(object value,
                                  Type targetType,
                                  object parameter,
                                  System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

After binding it has given alternate row background color to my listbox . But if listbox have too many rows when i scroll it Up and Down very fastly then row color changing because it is calling Converter once again while scrolling listbox.

How can i fix this, Please help me?

回答1:

You're seeing this behaviour as it's dependent upon the order the items the converter is called for. When you scroll the virtualised list this is not guaranteed to be sequential.

You need to perform the color selection based on something in the item.

You could either add a background property to the item directly or base the selection on a property of each item. For instance, if each item in the list had a sequential index you could change the converter to choose the color based on whether the index was odd or even.



回答2:

I had a very similar problem and ended up adding a new property onto the ViewModel items being displayed in the ListBox that had the colour/opacity set. Not great as it needed to be recalculated whenever anything was added to the list.



回答3:

Why not binding stackpanel background of your listbox datatemplate with the SolidColorBrush object in your viewmodel.And whether the item index of ObservalCollection is odd or even,the datatemplate can has themselves color.