4

I search for some way to show the items index in a ItemsControl that is using DataTemplate. So I found this good question. I used the idea in that question but all the values are zero! The only different between my code and the code in that question is that my controls (that is going to show the index) is not directly in the DataTemplate. It is in a Grid and the Grid is in the DataTemplate

Here is my code:

<ItemsControl ItemsSource="{Binding }">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                // column definitions
                <Label Content="{Binding RelativeSource={RelativeSource
                       Mode=TemplatedParent}, 
                       Path=(ItemsControl.AlternationIndex)}"/>
                // some other controls
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Result:

0
0
0
// and so on

What I expect to be shown:

0
1
2
// and so on

What is wrong whit this code?

Community
  • 1
  • 1
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
  • Did you do that: `Set AlternationCount on your ItemsControl to something greater than the max possible count of your items` (from the linked questions accepted answer)? – Florian Gl Feb 22 '13 at 10:01
  • Your code sais something different.^^ Just add `AlternationCount="1000"` so your ItemsControl and it should work. – Florian Gl Feb 22 '13 at 10:09

1 Answers1

12

The AlternationCount property of your property needs to be set.

<ItemsControl ItemsSource="{Binding }" AlternationCount={Binding CountOfItems}">
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Grid>
            // column definitions
            <Label Content="{Binding RelativeSource={RelativeSource
                   Mode=TemplatedParent}, 
                   Path=(ItemsControl.AlternationIndex)}"
                   />
            // some other controls
        </Grid>
    </DataTemplate>
</ItemsControl.ItemTemplate>

Mandelbrotter
  • 2,216
  • 2
  • 11
  • 28
Chrisjan Lodewyks
  • 1,162
  • 4
  • 13
  • 25
  • In the example above, if you'd like the `AlternationIndex` to be either `0` or `1`, set the `AlternationCount` to `2`. – Aaron Hoffman Feb 15 '17 at 00:03
  • @Chrisjan Lodewyks I can't have it working with a combobox. I use these properties for ComboBox: ItemsSource="{Binding ObjectName.ListName}" AlternationCount="{Binding ObjectName.ListName.Count}" . Any idea? – Romain Vincent May 04 '17 at 07:05