获取ListBoxItem - WPF的索引

本文关键字:索引 WPF ListBoxItem 获取 | 更新日期: 2023-09-27 17:50:28

如何获取ListBoxItem的索引?

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

获取ListBoxItem - WPF的索引

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

基本上你将ListBox的AlternationCount设置为非常高的值,并在每个项目上绑定AlternationIndex

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

您可以从ItemContainerGenerator中获得ListBoxItem的索引:

listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem);

属性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>