简体   繁体   中英

How to make alternating background color for ItemsControl rows (Silverlight)?

如何为ItemsControl行创建交替的背景颜色?

This is not built in function of ItemsControl . what you can do is extend ItemsControl for the requirement.

Nice example can found from here

I took the code from Joe McBride and generalized it to let you specify what property to set (defaults to Background ) and how many rows of each color before alternating (defaults to 1), and not require any external files.

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace Converters
{
    public class AlternatingRowConverter : IValueConverter
    {
        public Brush NormalBrush { get; set; }
        public Brush AlternateBrush { get; set; }
        public int AlternateEvery { get; set; }
        public string Property { get; set; }

        public AlternatingRowConverter()
        {
            AlternateEvery = 1;
            Property = "Background";
        }

        public object Convert(
            object value, Type targetType, object parameter, CultureInfo culture)
        {
            var element = (FrameworkElement)value;
            element.Loaded += Element_Loaded;

            return NormalBrush;
        }

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

        private void Element_Loaded(object sender, RoutedEventArgs e)
        {
            var element = (FrameworkElement)sender;

            DependencyObject obj = element;
            do
            {
                obj = VisualTreeHelper.GetParent(obj);
            } while (!(obj is ItemsControl) && obj != null);

            var parent = (ItemsControl)obj;
            if (parent != null)
            {
                DependencyObject container =
                    parent.ItemContainerGenerator.ContainerFromItem(
                    element.DataContext);

                if (container != null)
                {
                    int index = parent.ItemContainerGenerator.IndexFromContainer(
                        container);

                    if (index % (AlternateEvery * 2) >= AlternateEvery)
                        element.GetType().GetProperty(Property)
                            .SetValue(element, AlternateBrush, null);
                }
            }
        }
    }
}

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