R – How to determine index of current ListBox item from DataTemplate

datatriggerlistboxlistboxitemwpf

I have a ListBox. Now I want to write a DataTemplate in such way, that the first item will have red background and white background for other items. I guess I need to write a DataTrigger, but I have no idea how do determine that DataTemplate is applying to the first item.

Best Answer

items controls have an alternation count that you use to style against

have a look here :

<Style TargetType="{x:Type ListBoxItem}">
    <Style.Triggers>
        <Trigger Property="ItemsControl.AlternationIndex" Value="0">
            <Setter Property="Background" Value="LightBlue"></Setter>
        </Trigger>
        <Trigger Property="ItemsControl.AlternationIndex" Value="1">
            <Setter Property="Background" Value="LightGreen"></Setter>
        </Trigger>
    </Style.Triggers>
</Style>

enjoy!