I need a different background for odd and even elements ListBoxItem . I found a code that should solve my problem, but it doesn't want to work in UWP:
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="Orange"/>
</Trigger>
Are there any analogues to the property ItemsControl.AlternationIndex, or how can I specify the style of even and odd elements in VisualState?
Thanks in advance for your reply.
Currently in UWP, ListBox
does not provide related property for setting the background of the alternative rows.
We can create a CustomListBox
as a derived class of ListBox
to achieve our needs.
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;
}
}
}
}
Usage
<local:CustomListBox AlternativeBackground="Orange">
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem>Item 2</ListBoxItem>
<ListBoxItem>Item 3</ListBoxItem>
<ListBoxItem>Item 4</ListBoxItem>
</local:CustomListBox>