How to get the index of the current ItemsControl item?

herohuyongtao picture herohuyongtao · Mar 13, 2014 · Viewed 32.5k times · Source

Is there any way to get the index of the current ItemsControl item in WPF?

For example, I want to do something like:

<ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding current_index}">
            </TextBox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

so that after this, the first TextBox will show text "0", second "1", third "2" ....

Answer

FishySwede picture FishySwede · Mar 13, 2014

I would suggest looking at:

WPF ItemsControl the current ListItem Index in the ItemsSource

It explains how to work around the fact that there isn't a built in Index property on the ItemsControl.

EDIT:

I tried the following code:

<Window.Resources>
    <x:Array Type="{x:Type sys:String}" x:Key="MyArray">
        <sys:String>One</sys:String>
        <sys:String>Two</sys:String>
        <sys:String>Three</sys:String>
    </x:Array>
</Window.Resources>
<ItemsControl ItemsSource="{StaticResource MyArray}" AlternationCount="100" >
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=(ItemsControl.AlternationIndex), 
                RelativeSource={RelativeSource TemplatedParent}, 
                StringFormat={}Index is {0}}">
            </TextBlock>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl >

And get a window with three TextBlocks like:

[Index is 0]
[Index is 1]
[Index is 2]