为什么列表框交替索引总是返回 0



好的,我知道还有其他几个类似的问题,但我在让 AlternationIndex 在 ListBox 或 ListView 上工作时遇到了真正的问题。

我的 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。

疯狂的是,这仅适用于ListBox或ListView。

一旦我将其更改为 ItemsControl,索引是正确的,但我不想要项目控件,我想要一个包含它附带的所有功能的列表框。

如果您对为什么会发生这种情况有任何想法,我将不胜感激。

谢谢

基兰

对于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。

但是对于列表框,ListBoxItems是项目容器和数据模板将由内容演示器加载到ListBoxItem模板中。因此,ListBoxItemItemsControl.AlternationIndex 属性的值将根据索引而变化,但加载DataTemplateContentPresenterItemsControl.AlternationIndex 属性的值将始终为 0,这是默认值。

最新更新