2013-10-21 161 views
5

好吧,我知道還有一些其他類似的問題,但我有一個真正的問題,讓AlternationIndex在ListBox或ListView上工作。爲什麼ListBox的AlternationIndex總是返回0

我的XAML是這樣的:

  <ListBox BorderThickness="0" Name="RecentItemsListBox" HorizontalAlignment="Stretch" 
        ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
        ItemsSource="{Binding Path=RecentFilesList}" AlternationCount="100"> 
       <ListBox.ItemsPanel> 

        <ItemsPanelTemplate> 
         <WrapPanel /> 
        </ItemsPanelTemplate> 
       </ListBox.ItemsPanel> 

       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <StackPanel Orientation="Horizontal"> 
          <TextBlock Text="{Binding Path=(ItemsControl.AlternationIndex), 
            RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource IncCnvrtr}}" 
             Foreground="DimGray" FontSize="20" FontWeight="Bold" 
             HorizontalAlignment="Left" Margin="5,5,15,5" /> 
          <StackPanel VerticalAlignment="Center"> 
           <TextBlock Text="{Binding ClassName}" Foreground="Black" /> 
           <TextBlock Text="{Binding DisplayName}" Foreground="Black" /> 
          </StackPanel> 
         </StackPanel> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 
      </ListBox> 

轉換器遞增1.這工作得很好,我已經調試它來確認該值被髮送到轉換器的值始終爲0

的瘋狂的事情是這只是爲列表框或列表視圖

只要我將其更改爲一個ItemsControl索引是正確的,但我不想要一個項目控件,我想要一個列表框與它隨附的所有功能。

如果您有任何想法可能會發生這種情況,我會很感激您的幫助。

感謝

基蘭

回答

13

對於ListBoxListView你必須找到對ListBoxItem/ListViewItem如下屬性:

 <TextBlock Text="{Binding Path=(ItemsControl.AlternationIndex), 
         RelativeSource={RelativeSource AncestorType=ListBoxItem}, Converter={StaticResource IncCnvrtr}}" 
         Foreground="DimGray" FontSize="20" FontWeight="Bold" 
         HorizontalAlignment="Left" Margin="5,5,15,5" /> 

的差異是由於以下事實:ItemsControl只生成一個ContentPresenter成爲一個項目的容器,並且同樣的ContentPresenter也在加載DataTemplate。

但對於ListBoxListBoxItem是項目容器和DataTemplate將由ContentPresenterListBoxItemTemplate加載。所以ListBoxItemItemsControl.AlternationIndex屬性的值將根據索引而改變,但的ItemsControl.AlternationIndex屬性的值加載DataTemplate將始終爲0,這是默認值。

+0

好的,這是有道理的,引用ListBoxItem完美的作品,謝謝。 – Kezza

相關問題