获取ListBoxItem - WPF的索引
本文关键字:索引 WPF ListBoxItem 获取 | 更新日期: 2023-09-27 17:50:28
如何获取ListBoxItem
的索引?
ListBox
通过XmlDataProvider
绑定到XML节点集合
我有一个类似的问题,在这里得到了回答
基本上你将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);
属性SelectedIndex
可以工作。这完全取决于你如何绑定
你可能想要绑定SelectedIndex
依赖属性到连接到它的数据上下文的对象的某些属性,例如
<ListBox SelectedIndex="{Binding MySelectedIndex}" ItemsSource="{Binding MyItems}"/>
但是你显然可以这样做
<ListBox SelectedIndex="{Binding MySelectedIndex}">
<ListBoxItem>1</ListBoxItem>
<ListBoxItem>2</ListBoxItem>
<ListBoxItem>3</ListBoxItem>
<ListBoxItem>4</ListBoxItem>
</ListBox>