How to determine index of current ListBox item from DataTemplate?
Asked Answered
C

1

5

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.

Cleaning answered 15/11, 2009 at 10:47 Comment(0)
M
7

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!

Maryannemarybella answered 15/11, 2009 at 11:14 Comment(3)
It's great feature, thanks for info. But I need only first item to have red background, not every item where (itemIndex % AlternationCount) == 0. Of course, I can bind AlternationCount to ItemsSource.Count, but isn't there any better way to do this?Cleaning
what you outline sounds acceptable, its all in xaml. it gets the job done, and you can move on to better things. someone else might come up with a more elegant solution. you could do a multibinding with the first binding binding to the current item and the second an ancestor binding, binding to the list box's itemssource. then in your converter you could check what the index of the item was. but your solution above is all in xaml. i always favor readability. its in plain sight in the xaml, not locked away in a converterMaryannemarybella
No need to bind AlternationCount to ItemsSource.Count: Just set it to Int32.MaxValue in the XAML. (I prefer AlternationCount="2147483647" over using "{x:Static sys:Int32.Maxvalue}", since it is faster and 2^31-1 is recognizable to most programmers).Connecticut

© 2022 - 2024 — McMap. All rights reserved.