为什么AlternationIndex为ItemsControl中的所有项返回0?(Why AlternationIndex returns 0 for all items in ItemsControl?)

我搜索某种方式来显示使用DataTemplate的ItemsControl中的项目索引。 所以我找到了这个好问题。 我在这个问题中使用了这个想法,但所有的值都是零! 我的代码和这个问题中的代码唯一不同的是,我的控件(即将显示索引)不直接在DataTemplate 。 它位于Grid , Grid位于DataTemplate

这是我的代码:

<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>

结果:

0 0 0 // and so on

我期望显示的是:

0 1 2 // and so on

这个代码有什么问题?

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?

最满意答案

需要设置属性的AlternationCount属性。

<ItemsControl ItemsSource="{Binding }" AlterationCount={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>

The AlternationCount property of your property needs to be set.

<ItemsControl ItemsSource="{Binding }" AlterationCount={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>

更多推荐