获取ListBoxItem的索引 - WPF

5

如何获取 ListBoxItem 的索引?

ListBox 通过 XmlDataProvider 绑定到 XML 节点的集合。

3个回答

14

我有一个类似的问题,这个问题在这里被回答了。

基本上你需要将ListBox的AlternationCount设置为一个很大的数值,并绑定每个项的AlternationIndex

<ListBox AlternationCount="100">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},
                                      Path=(ItemsControl.AlternationIndex)}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

@Greg:同意,但这是我目前在使用ListBox时找到的唯一方法。我希望他们在未来的WPF版本中添加一个属性。 - Rachel
@punker76 我认为 ListBoxes 默认是虚拟化的,因此不应该出现这种情况。 - Rachel
1
@Rachel 好的,虚拟化是默认的,但交替索引不起作用。我创建了一个小项目,请尝试向下和向上滚动,您会看到 http://jkarger.de/WpfStackOverflowSpielWiese.exe (.net 4) - punker76

12
您可以从ItemContainerGenerator中获取ListBoxItem的索引:
listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem);

当使用ItemsSource并且具有相同引用时,这种方法比接受的答案效果更好。 - Anes08

-4

属性SelectedIndex是可行的。这完全取决于您如何进行绑定。

您可能希望将SelectedIndex依赖属性绑定到连接到其数据上下文的对象的某个属性,例如:

<ListBox SelectedIndex="{Binding MySelectedIndex}" ItemsSource="{Binding MyItems}"/>

但你显然可以这样做

<ListBox SelectedIndex="{Binding MySelectedIndex}">
  <ListBoxItem>1</ListBoxItem>
  <ListBoxItem>2</ListBoxItem>
  <ListBoxItem>3</ListBoxItem>
  <ListBoxItem>4</ListBoxItem>
</ListBox>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接