7

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

我的xml是这样的:

            <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,索引是正确的,但我不想要项目控件,我想要一个包含所有功能的列表框。

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

谢谢

基兰

4

1 回答 1

22

For ListBoxor ListViewyou will have to find the property on the 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" />

The difference is due the fact that ItemsControl only generates a single ContentPresenter which becomes the Container of an item, and the same ContentPresenter is also loading the DataTemplate.

But for ListBox, ListBoxItems are the item containers and DataTemplate will be loaded by the ContentPresenter in Template of ListBoxItem. So value of ListBoxItem's ItemsControl.AlternationIndex property will change according to the index but the value of the ItemsControl.AlternationIndex property of the ContentPresenter that loads the DataTemplate will always be 0, which is the default value.

于 2013-10-21T10:13:45.287 回答