是否可以在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>
Run Code Online (Sandbox Code Playgroud)
它看起来像这样:
我希望能够在DataTemplate中显示索引值,但我不希望数据由模型或视图模型保留或支持.换句话说,如果OC中项目的顺序发生变化,我不想重新计算索引.该值应与OC中的基础索引固有关联.如果索引从0开始是可以的(实际上,我希望它).
其他人使用的一种方法是AlternationIndex AP,但这在某些情况下有其自身的缺陷.
最后一个想法:我不禁想到转换器将在最终解决方案中发挥作用.
我搜索某种方式来显示ItemsControl
正在使用的项目索引DataTemplate
.所以我发现了这个好问题.我在那个问题中使用了这个想法,但所有的值都是零!我的代码和该问题中的代码之间唯一不同的是我的控件(即将显示索引)不是直接在DataTemplate
.它在a Grid
和Grid
in中DataTemplate
这是我的代码:
<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>
Run Code Online (Sandbox Code Playgroud)
结果:
0
0
0
// and so on
Run Code Online (Sandbox Code Playgroud)
我希望展示的内容:
0
1
2
// and so on
Run Code Online (Sandbox Code Playgroud)
这段代码有什么问题?
列表框是数据绑定,通过xmldataprovider绑定到XML节点的集合.