问题描述
我需要一个用于偶数元素ListBoxItem的不同背景。我找到了可以解决我的问题的代码,但是它不想在UWP中工作:
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="Orange"/>
</Trigger>
属性ItemsControl.AlternationIndex是否有任何类似形式,或者如何在VisualState中指定偶数和奇数元素的样式?
预先感谢您的答复。
解决方法
当前在UWP中,ListBox
不提供用于设置备用行背景的相关属性。
我们可以创建CustomListBox
作为ListBox
的派生类来满足我们的需求。
public class CustomListBox : ListBox
{
public Brush AlternativeBackground
{
get { return (Brush)GetValue(AlternativeBackgroundProperty); }
set { SetValue(AlternativeBackgroundProperty,value); }
}
public static readonly DependencyProperty AlternativeBackgroundProperty =
DependencyProperty.Register("AlternativeBackground",typeof(Brush),typeof(CustomListBox),new PropertyMetadata(null));
protected override void PrepareContainerForItemOverride(DependencyObject element,object item)
{
base.PrepareContainerForItemOverride(element,item);
var listBoxItem = element as ListBoxItem;
if (listBoxItem != null)
{
var index = IndexFromContainer(element);
if ((index + 1) % 2 != 1)
{
listBoxItem.Background = AlternativeBackground;
}
}
}
}
用法
<local:CustomListBox AlternativeBackground="Orange">
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem>Item 2</ListBoxItem>
<ListBoxItem>Item 3</ListBoxItem>
<ListBoxItem>Item 4</ListBoxItem>
</local:CustomListBox>
,
您可以使用Microsoft.Toolkit.Uwp.UI.Extensions,它可以帮助您设置AlternateColor
和AlternateItemTemplate
。
有关更多信息,您可以下载Windows Community Toolkit。