Greg
Greg

Reputation: 1367

Get index of ListBoxItem - WPF

How do I get the index of a ListBoxItem?

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

Upvotes: 6

Views: 15374

Answers (3)

Christian Regli
Christian Regli

Reputation: 2246

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

listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem);

Upvotes: 13

Rachel
Rachel

Reputation: 132558

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>

Upvotes: 14

Jose
Jose

Reputation: 11091

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>

Upvotes: -4

Related Questions