如何获取当前 ItemsControl 项的索引? [英] How to get the index of the current ItemsControl item?

查看:47
本文介绍了如何获取当前 ItemsControl 项的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法可以得到WPF中当前ItemsControl项的索引?

Is there any way to get the index of the current ItemsControl item in WPF?

例如,我想做这样的事情:

For example, I want to do something like:

<ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding current_index}">
            </TextBox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

以便在此之后,第一个 TextBox 将显示文本 "0",第二个 "1",第三个 "2" ....

so that after this, the first TextBox will show text "0", second "1", third "2" ....

推荐答案

我建议看:

WPF ItemsControl ItemsSource 中的当前 ListItem 索引

它解释了如何解决 ItemsControl 上没有内置 Index 属性这一事实.

It explains how to work around the fact that there isn't a built in Index property on the ItemsControl.

我尝试了以下代码:

<Window.Resources>
    <x:Array Type="{x:Type sys:String}" x:Key="MyArray">
        <sys:String>One</sys:String>
        <sys:String>Two</sys:String>
        <sys:String>Three</sys:String>
    </x:Array>
</Window.Resources>
<ItemsControl ItemsSource="{StaticResource MyArray}" AlternationCount="100" >
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=(ItemsControl.AlternationIndex), 
                RelativeSource={RelativeSource TemplatedParent}, 
                StringFormat={}Index is {0}}">
            </TextBlock>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl >

并获得一个包含三个 TextBlock 的窗口,例如:

And get a window with three TextBlocks like:

[Index is 0]
[Index is 1]
[Index is 2]

这篇关于如何获取当前 ItemsControl 项的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆