DimaBond
DimaBond

Reputation: 61

UWP Different styles for odd and even elements ListBoxItem

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.

Upvotes: 2

Views: 165

Answers (2)

Vincent
Vincent

Reputation: 3304

You can use Microsoft.Toolkit.Uwp.UI.Extensions, which helps you set AlternateColor & AlternateItemTemplate. For more info, you can download Windows Community Toolkit.

enter image description here

Upvotes: 1

Anran Zhang
Anran Zhang

Reputation: 7727

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>

Upvotes: 3

Related Questions