WPF - Bind to Item Index from within ItemTemplate of ItemsControl?

Rachel picture Rachel · Aug 10, 2010 · Viewed 22.9k times · Source

Is there a way to bind to the ItemIndex from within the ItemTemplate of an ItemsControl?

For example:

<ItemsControl ItemsSource="{Binding Path=ItemList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=ThisItemsIndex}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Answer

John Bowen picture John Bowen · Aug 10, 2010

If you're not using any type of alternating row styles you might be able to hijack the AlternationIndex for this. Set AlternationCount on your ItemsControl to something greater than the max possible count of your items and then use

Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=(ItemsControl.AlternationIndex)}"

Edit: As bradgonesurfing pointed out in comments, this is not recommended if you're using virtualization, as it will only index the items that are generated and not the entire list.