【发布时间】:2011-09-24 13:37:06
【问题描述】:
是否可以知道 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>
看起来像这样:
【问题讨论】:
-
一种方法是创建一个自定义的 IValueConverter 并将 items 属性作为参数传递,然后通过查看集合来获取索引,尽管这不是很有效。
-
这也不可靠。如果它被 CollectionViewSource 过滤或排序怎么办?聪明,我承认,但还有更好的方法。
标签: wpf indexing itemscontrol