为什么ListBox AlternationIndex总是返回0

Kez*_*zza 6 wpf listbox alternation

好吧,我知道还有其他几个类似的问题,但我有一个真正的问题,让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>
Run Code Online (Sandbox Code Playgroud)

转换器将值递增1.这很好,我调试它以确认发送到转换器的值始终为0.

疯狂的是这只适用于ListBox或ListView

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

如果你知道为什么会发生这种情况,我将非常感谢你的帮助.

谢谢

基兰

Nit*_*tin 15

对于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" />
Run Code Online (Sandbox Code Playgroud)

不同之处在于,ItemsControl只生成一个ContentPresenter,它成为项目的Container,同样ContentPresenter也是加载DataTemplate.

ListBox,ListBoxItem是该项目的容器和DataTemplate将被装载ContentPresenterTemplateListBoxItem.因此,价值ListBoxItemItemsControl.AlternationIndex财产将根据索引,但的值更改ItemsControl.AlternationIndex的属性ContentPresenter加载的DataTemplate将始终为0,这是默认值.

  • 这个框架的反直觉从来没有让我着迷。似乎为了理解它,您必须在与编写库本身的水平几乎相似的水平上了解它。我想权力伴随着责任。 (2认同)