WPF ItemsControl ItemsSource中的当前ListItem索引 [英] WPF ItemsControl the current ListItem Index in the ItemsSource
本文介绍了WPF ItemsControl ItemsSource中的当前ListItem索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在ItemsControl中知道当前项目的索引?
Is it possible to know the current item's Index in a 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>
<StackPanel Margin="10">
<!-- one -->
<TextBlock Text="{Binding Path=.,
StringFormat={}Value is {0}}" />
<!-- two -->
<TextBlock Text="{Binding Path=(ItemsControl.AlternationIndex),
RelativeSource={RelativeSource TemplatedParent},
FallbackValue=FAIL,
StringFormat={}Index is {0}}" />
<!-- three -->
<TextBlock Text="{Binding Path=Items.Count,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ItemsControl}},
StringFormat={}Total is {0}}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
看起来像这样:
< img src =https://i.stack.imgur.com/Dnysv.pngalt =在此处输入图像说明>
推荐答案
我刚才问了同样的事情这里
I asked the same thing a while ago here
没有内置索引属性,但您可以将ItemsControl的 AlternationCount
设置为高于项目数的值,并绑定到 AlternationIndex
There isn't a built in Index property, but you can set the AlternationCount
of your ItemsControl to something higher than your item count, and bind to the AlternationIndex
<TextBlock Text="{Binding
Path=(ItemsControl.AlternationIndex),
RelativeSource={RelativeSource Mode=TemplatedParent},
FallbackValue=FAIL,
StringFormat={}Index is {0}}" />
应该注意,如果ListBox使用虚拟化作为这里指出了一个网络指南。
It should be noted that this solution may not work if your ListBox uses Virtualization as bradgonesurfing pointed out here.
这篇关于WPF ItemsControl ItemsSource中的当前ListItem索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文