[英]Get index of ListBoxItem - WPF
如何獲取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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.