[英]Get index of ListBoxItem - WPF
How do I get the index of a ListBoxItem
?如何获取
ListBoxItem
的索引?
The ListBox
has binding to a collection of XML nodes through XmlDataProvider
. ListBox
通过XmlDataProvider
绑定到一组 XML 节点。
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
设置为非常高的值,并绑定到每个项目的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);
The property SelectedIndex
would work. SelectedIndex
属性会起作用。 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 eg您可能希望将
SelectedIndex
依赖属性绑定到连接到它的数据上下文的对象的某些属性,例如
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.