2011-04-19 114 views

回答

5

我這是回答here

基本上你設定ListBox的AlternationCount的東西實在是高,並綁定到AlternationIndex上類似的問題每件商品

<ListBox AlternationCount="100"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, 
             Path=(ItemsControl.AlternationIndex)}" /> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 
+0

沒有理想的解決方案,雖然... – Greg 2011-04-20 14:05:18

+0

@格雷格:您可以同時從ItemContainerGenerator得到一個ListBoxItem的指數表示同意,但它是我發現了一個ListBox做到這一點,到目前爲止的唯一途徑。我希望他們在未來版本的WPF中添加一個屬性 – Rachel 2011-04-20 14:16:02

+0

注意:這不適用於虛擬化列表框! – punker76 2013-02-20 15:13:17

0

財產SelectedIndex將工作。這一切都取決於你如何進行綁定

您可能想要將SelectedIndex依賴項屬性綁定到與其datacontext相關的對象的某個屬性,例如,

<ListBox SelectedIndex="{Binding MySelectedIndex}" ItemsSource="{Binding MyItems}"/> 

,但你能明顯做到這一點

<ListBox SelectedIndex="{Binding MySelectedIndex}"> 
    <ListBoxItem>1</ListBoxItem> 
    <ListBoxItem>2</ListBoxItem> 
    <ListBoxItem>3</ListBoxItem> 
    <ListBoxItem>4</ListBoxItem> 
</ListBox> 
2

Y

ItemContainerGenerator.IndexFromContainer(my_listBoxItem);