WPF - 从ItemsControl的ItemTemplate中绑定到项目索引?

Rac*_*hel 24 data-binding wpf itemscontrol

有没有办法从ItemsControl的ItemTemplate中绑定到ItemIndex?

例如:

<ItemsControl ItemsSource="{Binding Path=ItemList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=ThisItemsIndex}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)

Joh*_*wen 27

如果您没有使用任何类型的交替行样式,您可能会为此劫持AlternationIndex.将ItemsControl上的AlternationCount设置为大于项目的最大可能计数,然后使用

Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=(ItemsControl.AlternationIndex)}"
Run Code Online (Sandbox Code Playgroud)

编辑:正如bradgonesurfing在评论中指出的那样,如果您使用虚拟化,则不建议这样做,因为它只会索引生成的项而不是整个列表.

  • 不要这样做.见http://stackoverflow.com/questions/6511180/wpf-itemscontrol-the-current-listitem-index-in-the-itemssource/17962582#17962582 (5认同)