簡體   English   中英

獲取 ListBoxItem 的索引 - WPF

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM