简体   繁体   中英

Using the index of an item in a repeater view in Xamarin forms

I have a repeater view which's item source is an observable collection of view models and which has a data template. Now I want to use the index of the specific item to be used inside the data template. Is there any way to achieve this? NOTE: The repeater view is part of UXDivers.Artina Library, but it should expose the same API as a listview and thus a solution that would work for a listview, would probably also work for the repeater.

Here is the code I have so far:

Xaml:

<ctlRep:Repeater
        ItemsSource="{ Binding ListItems }"
        Padding="10, 10"
        Spacing="10"
        Orientation="Vertical">
        <ctlRep:Repeater.ItemTemplate>
            <DataTemplate>
                <elements:StructuredVideoDescriptionItemTemplate />
            </DataTemplate>
        </ctlRep:Repeater.ItemTemplate>
</ctlRep:Repeater>

Viewmodel:

public class VideoDescriptionStructureListItem : ObservableObject
{
    public string Title { get; set; }
    public bool IsNumberic { get; set; }
    public ObservableCollection<string> ListItems { get; set; }
}

Inside the data template I would like to have access to the ListItems item (which is a string) and the index of the specific item.

It may not be the solution you are looking for, but I have solved the exact issue lately with the following strategy

  • Introduce an intermediate object that contains a property for an index
  • Build an ObservableCollection of those objects instead of string objects and assign the correct indices
  • Bind to the string and the index instead of the direct object

The class may look like this:

class VideoDescriptionViewModel
{
    public string Description { get; private set; }
    public int Index { get; private set; }

    public VideoDescriptionViewModel(string description, int index)
    {
        Description = description;
        Index = index;
    }
}

and you can build the instances like

var videoDescriptionViewModels = videoDescriptions.Select((description, index) => new VideoDescriptionViewModel(description, index));

and bind it from your XAML

<elements:StructuredVideoDescriptionItemTemplate Description="{Binding Description}" 
                                                 Id="{Binding Id}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM