4

How do I get the index of a ListBoxItem?

The ListBox has binding to a collection of XML nodes through XmlDataProvider.

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
Greg
  • 1,227
  • 5
  • 23
  • 52

3 Answers3

13

I had a similar question which was answered here

Basically you set the ListBox's AlternationCount to something really high, and bind to the AlternationIndex on each item

<ListBox AlternationCount="100">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},
                                      Path=(ItemsControl.AlternationIndex)}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Community
  • 1
  • 1
Rachel
  • 130,264
  • 66
  • 304
  • 490
  • @Greg: Agreed, but it's the only way I've found to do it so far with a ListBox. I'm hoping they add a property in some future version of WPF – Rachel Apr 20 '11 at 14:16
  • @punker76 I think ListBoxes are Virtualized by default, so that shouldn't be the case – Rachel Feb 20 '13 at 15:24
  • 1
    @Rachel ok, virtualisation is the default, but the alternation index doesn't works. i created a little project, try scrolling down and up and you will see http://jkarger.de/WpfStackOverflowSpielWiese.exe (.net 4) – punker76 Feb 20 '13 at 19:17
12

You can get the index of the ListBoxItem from the ItemContainerGenerator:

listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem);
Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
Ketobomb
  • 2,108
  • 1
  • 17
  • 27
  • This works better than the accepted answer when using ItemsSource while having identical references – Anes08 Jul 31 '23 at 11:35
-4

The property SelectedIndex would work. It all depends on how you're doing your binding

You probably want to bind the SelectedIndex dependency property to some property of the object connected to it's datacontext e.g.

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

but you could obviously do this

<ListBox SelectedIndex="{Binding MySelectedIndex}">
  <ListBoxItem>1</ListBoxItem>
  <ListBoxItem>2</ListBoxItem>
  <ListBoxItem>3</ListBoxItem>
  <ListBoxItem>4</ListBoxItem>
</ListBox>
Jose
  • 10,891
  • 19
  • 67
  • 89