为什么 ListBox 的 AlternationIndex 总是返回 0?

7

好的,我知道还有其他类似的问题,但我在使用ListBox或ListView时遇到了AlternationIndex无法正常工作的问题。

我的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,索引就是正确的,但我不想要一个ItemsControl,我想要一个带有所有附带功能的ListBox。
如果您有任何想法,为什么会发生这种情况,我将非常感激您的帮助。
谢谢
Kieran
1个回答

23

对于 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,这就是差异所在。但对于 ListBox,ListBoxItem 是项容器,DataTemplate 将由 ListBoxItem 模板中的 ContentPresenter 加载。因此,ListBoxItemItemsControl.AlternationIndex 属性值将根据索引而改变,但加载 DataTemplate 的 ContentPresenter 的 ItemsControl.AlternationIndex 属性值始终为 0(默认值)。

好的,那很有道理,引用 ListBoxItem 完美地解决了问题,谢谢。 - Kezza
2
这个框架的反直觉性让我始终感到困惑。似乎为了理解它,你必须在实际上与编写库本身的人相似的水平上了解它。我想,随着权力的增加,责任也随之而来。 - j riv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接