如何为ItemsControl行创建交替的背景颜色?
答案 0 :(得分:6)
这不是ItemsControl
的功能。您可以做的是扩展ItemsControl
以满足要求。
可以从here
找到很好的例子答案 1 :(得分:2)
我从Joe McBride获取代码并将其概括为允许您指定要设置的属性(默认为Background
)以及交替前每种颜色的行数(默认为1),而不是需要任何外部文件。
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);
}
}
}
}
}