为什么ItemsControl中的所有项的AlternationIndex都返回0?

4
我正在寻找一种方法,在使用 DataTemplate 的 ItemsControl 中显示项目索引。所以我发现了这个好问题this。我使用了那个问题中的思路,但是所有的值都是零!唯一不同的是我的控件(将要显示索引)不直接在 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

这段代码有什么问题?

你是否按照链接中被接受的答案所述,将ItemsControl的AlternationCount设置为大于项目最大可能计数的值? - Florian Gl
你的代码说了一些不同的话。^^只需在你的ItemsControl中添加AlternationCount="1000",它就应该可以工作了。 - Florian Gl
1个回答

12
你的属性的 AlternationCount 属性需要设置。
<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>


在上面的例子中,如果您希望“AlternationIndex”为“0”或“1”,请将“AlternationCount”设置为“2”。 - Aaron Hoffman
@Chrisjan Lodewyks 我无法让它与组合框一起工作。我使用以下属性来设置ComboBox:ItemsSource =“{Binding ObjectName.ListName}” AlternationCount =“{Binding ObjectName.ListName.Count}”。有什么想法吗? - Romain Vincent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接