Collectionview scrolls back to first item index

65 Views Asked by At

I am building my app in .Net Maui, but I'm having an issue with the collectionView. I have a collection of hymns retrieved from a json file which is used to populate my CollectionView. Whenever a user clicks on a hymn, it navigates to the hymn details page. However, when the user exits the details page, it navigates to the first item in the collectionView instead of the item or hymn title the user clicked on. Please is there anyway to make my collectionview remember the last selected item and scroll there, or better yet remain there. Thank you.

Here is the CollectionView in the HymnList.xaml

<CollectionView
    x:Name="hymnCollection"
    ItemsSource="{Binding FilteredHymns}"
   SelectionChanged="CollectionView_SelectionChanged"
    SelectionMode="Single"
   VerticalScrollBarVisibility="Always">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Label Text="{Binding title}"/>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

Here is the navigation in the codebehind

private async void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.CurrentSelection.FirstOrDefault() is Hymn selectedHymn)
    {
        await Navigation.PushModalAsync(new HymnDetailPage(selectedHymn));
    }
}

Here is a sample of my hymndetailspage.xaml.cs

Hymn _selectedHymn;
public HymnDetailPage(Hymn selectedHymn)
{
    _selectedHymn = selectedHymn;
    InitializeComponent();
    BindingContext = this;

    GetHymnList(selectedHymn);
}

private void GetHymnList(Hymn selectedHymn)
{
    int verseNum = 1;
    titlelbl.Text = selectedHymn.title;
    numlbl.Text = $"{selectedHymn.number}";
    foreach (string verse in selectedHymn.verses)
    {
        verseslbl.Text += $"{verseNum}";
        verseslbl.Text += ".";
        verseslbl.Text += ("\n");
        verseslbl.Text += verse;
        verseslbl.Text += ("\n\n");
        verseNum++;
    }
}

private async void BackButton_Clicked(object sender, EventArgs e)
{
    await Navigation.PopModalAsync();
}

I tried mocking it with a simple list of names but still the issue persists

0

There are 0 best solutions below