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

问题描述 投票:4回答:1

我正在寻找某种方式来显示正在使用ItemsControlDataTemplate中的项目索引。因此,我发现了this的好问题。我在那个问题中使用了这个主意,但是所有值都是零!我的代码与该问题中的代码之间的唯一区别是,我的控件(将显示索引)不直接位于DataTemplate中。它在Grid中,而GridDataTemplate中]

这是我的代码:

<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

此代码有什么问题?

c# wpf datatemplate itemscontrol
1个回答
10
投票

需要设置属性的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>

© www.soinside.com 2019 - 2024. All rights reserved.