如何获取 ListBoxItem
的索引?
ListBox
通过 XmlDataProvider
绑定到 XML 节点的集合。
如何获取 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>