Jerry Nixon on Windows: What’s the Index of the Current WPF ItemsControlItem?

Jerry Nixon on Windows

Tuesday, July 19, 2011

What’s the Index of the Current WPF ItemsControlItem?

If you want to know the index of an item in an ItemsControl collection, you really cannot do it. However, there's a barely-reliable workaround by using the AlternationCount. As long as you set the AlternationCount of the ItemsControl higher than the potential number of ItemsControl items, then it will work. The downside is, clearly, you no longer can use the AlternationCount for what it was designed to do (mostly just creating green bar-like alternating styles).

Anyway, here's how you do it:

    <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>
                <StackPanel Margin="10">
                    <!--  value of the data -->
                    <TextBlock Text="{Binding Path=., StringFormat={}Value is {0}}" />
                    <!--  index of the item -->
                    <TextBlock Text="{Binding Path=(ItemsControl.AlternationIndex), 
                        RelativeSource={RelativeSource TemplatedParent}}" />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>