Nickon
Nickon

Reputation: 10156

Binding to ObservableCollection's index

I have a problem. I bound ListView to my ObservableCollection<ImageSource>:

<ListView x:Name="FramesListView" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Disabled"
      ItemsSource="{Binding Path=FrameImages}" SelectionChanged="FramesListView_OnSelectionChanged">
<ListView.ItemsPanel>
    <ItemsPanelTemplate>
        <WrapPanel
            Width="Auto"
            ItemWidth="{Binding (ListView.View).ItemWidth, RelativeSource={RelativeSource AncestorType=ListView}}"
            ItemHeight="{Binding (ListView.View).ItemHeight, RelativeSource={RelativeSource AncestorType=ListView}}" />
    </ItemsPanelTemplate>
</ListView.ItemsPanel>

<ListView.ItemTemplate>
    <DataTemplate>
        <Border Width="100" Height="75" BorderThickness="1" BorderBrush="DarkGray" VerticalAlignment="Center" Margin="7,5,7,5">
            <StackPanel Orientation="Vertical">
                <Image Margin="5,5,5,5" Width="100" Height="75" Source="{Binding}" Stretch="Fill"></Image>
                <Label HorizontalAlignment="Center" Content="{Binding}"></Label>
            </StackPanel>
        </Border>
    </DataTemplate>
</ListView.ItemTemplate>
</ListView>

Everything works fine except one thing. I also wanted to show indexes under each image. I don't know how to realize this.

How to change that line to make it possible?

<Label HorizontalAlignment="Center" Content="{Binding}"></Label>

Upvotes: 1

Views: 1829

Answers (1)

Mohammad
Mohammad

Reputation: 1990

A somewhat hackish solution I used onetime in a similar situation was to use the AlternationIndex property for this purpose. By setting the AlternationCount to a high enough number the AlternationIndex property can serve as a counter.

<ItemsControl x:Name="itemsControl" AlternationCount="100000">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding Path='(ItemsControl.AlternationIndex)', RelativeSource={RelativeSource AncestorType=ContentPresenter}}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

This however has a drawback that numbering starts from 0.

Another cleaner solution includes creating a ValueConverter as discussed here: How can I bind against the Index of a ListBoxItem

Upvotes: 2

Related Questions