How do I get the index of a listboxitem in a WPF listbox instance?

浪尽此生 提交于 2019-12-02 10:59:16

问题


The listbox is databound, binding to a collection of XML nodes through xmldataprovider.


回答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>



回答2:


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

ItemContainerGenerator.IndexFromContainer(my_listBoxItem);



回答3:


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>


来源:https://stackoverflow.com/questions/5716073/how-do-i-get-the-index-of-a-listboxitem-in-a-wpf-listbox-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!