Get index of ListBoxItem - WPF
12,555
Solution 1
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>
Solution 2
You can get the index of the ListBoxItem
from the ItemContainerGenerator
:
listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem);
Author by
Greg
Programming, cursing, riding my bikes and learning foreign languages.
Updated on June 04, 2022Comments
-
Greg about 2 years
How do I get the index of a
ListBoxItem
?The
ListBox
has binding to a collection of XML nodes throughXmlDataProvider
. -
Rachel about 13 years@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 over 11 years@punker76 I think ListBoxes are Virtualized by default, so that shouldn't be the case
-
punker76 over 11 years@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 jkarger.de/WpfStackOverflowSpielWiese.exe (.net 4)