简体   繁体   中英

How to select a color from a list of colors continuously?

I have a ListView in which I'm drawing rectangles one below another and I'm simulating infinite scrolling of rectangles by incremental loading.

I want to set a different color to each rectangle in the ListView.

I'm implementing this using a Binding Converter.

My problem is that the color selected once will not remain the same. If I scroll down through the ListView and scroll back up, the color for some rectangles would change!

Xaml:

<ListView ItemSource={Binding items}>
<ListView.ItemTemplate>
<DataTemplate>
<Rectangle Fill="{Binding Converter={StaticResource gridColorConverter},
                                  Mode=OneTime}" />
</ListView.ItemTemplate>
</DataTemplate>
</ListView>

C#:

public class GridColorConverter : IValueConverter
    {
        public static int SelectedColorIndex = 0;

        public static SolidColorBrush Pink = new SolidColorBrush(Color.FromArgb(255, 90, 20, 66));
        public static SolidColorBrush Purple = new SolidColorBrush(Color.FromArgb(255, 85, 29, 108));
        public static SolidColorBrush Green = new SolidColorBrush(Color.FromArgb(255, 39, 121, 85));
        public static SolidColorBrush Brown = new SolidColorBrush(Color.FromArgb(255, 109, 26, 21));
        public static SolidColorBrush Blue = new SolidColorBrush(Color.FromArgb(255, 30, 89, 105));

        public static List<SolidColorBrush> GridColors = new List<SolidColorBrush>() { Pink, Green, Purple, Brown, Blue };

        public object Convert(object value, Type targetType, object parameter, string language)
        {
           if(SelectedColorIndex > (GridColors.Count - 1))
           {
               SelectedColorIndex = 0;
           }
           return GridColors[SelectedColorIndex++];
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return null;
        }
    }

You need to use some property of your item in the converter to ensure it always yields the same color. You could do something like return GridColors[value.GetHashCode() % GridColors.Count] , but it would be better to cast the value to its actual view model type and use an incremental index property you'd add to the item view model to make sure neighboring items don't yield the same color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM