Numbered listbox

Finally! If found a way much more elegant and probably with better performance either.
(see also Accessing an ItemsControl item as it is added)

We “misuse” the property ItemsControl.AlternateIndex for this. Originally it is intended to handle every other row within a ListBox differently. (see http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.alternationcount.aspx)

1. Set AlternatingCount to the amount of items contained in the ListBox

<ListBox ItemsSource="{Binding Path=MyListItems}"
         AlternationCount="{Binding Path=MyListItems.Count}"
         ItemTemplate="{StaticResource MyItemTemplate}"
...
/>

2. Bind to AlternatingIndex your DataTemplate

<DataTemplate x:Key="MyItemTemplate" ... >
    <StackPanel>
        <Label Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=TemplatedParent.(ItemsControl.AlternationIndex)}" />
        ...
    </StackPanel>
</DataTemplate>

So this works without a converter, an extra CollectionViewSource and most importantly without brute-force-searching the source collection.

Leave a Comment