Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScrollTo not working with grouped ListView in Xamarin.Forms

I have a TabbedPage and it contains a few ContentPage that are consisting of a ContentView and some of them has a ListView.

The ListView contains a grouped ItemsSource represented by a custom model class:

public class DataGroup: List<DataGroupItem>
{   
    public string HeaderText { get; set; }

    public string ShortName { get; set; } 

    public string SubTitle { get; set; }

    public DataGroup(string headerText, string shortName)
    {
        HeaderText= headerText;
        ShortName= shortName;
    }
}

The XAML code (it has an ItemTemplate as well):

<ListView x:Name="listView"
              Grid.Row="0"
              GroupDisplayBinding="{Binding HeaderText}"
              GroupShortNameBinding="{Binding ShortName}"
              HasUnevenRows="True"
              IsGroupingEnabled="True"
              ItemsSource="{Binding DataGroups}"
              SeparatorColor="Black"
              SeparatorVisibility="Default">
    ...
</ListView>

When I change the actual tab, I need the ListView to be scrolled to a certain group.

I use this code:

ObservableCollection<DataGroup> dataGroups
    = this.listView.ItemsSource as ObservableCollection<DataGroup>;
if (scrolling)
{        
    var res = dataGroups.Where(dg=>dg.ItemCount > 3).LastOrDefault();
    if (res != null)
        //Device.StartTimer(TimeSpan.FromMilliseconds(150), () =>
        //{
            this.listView.ScrollTo(res, ScrollToPosition.Center, false);
            //return false;
        //});
}

I tried all variations in ScrollToPosition, unfortunately, nothing happens.

What else should I try?

like image 780
Nestor Avatar asked Sep 07 '25 19:09

Nestor


2 Answers

Well, it was quite an adventure to figure this out.

First, I thought I should set a child item as the target of the ScrollTo method, but it changed nothing.

As a vague idea, I added the SelectedItem into the soup, and it worked, so I have this as a final result:

ObservableCollection<DataGroup> dataGroups= this.listView.ItemsSource as ObservableCollection<DataGroup>;
if (scrolling)
{        
  var res = dataGroups.Where(dg=>dg.ItemCount > 3).LastOrDefault();
  if (res != null && res.Count > 0)
  {
    this.listView.SelectedItem = res[0];
    this.listView.ScrollTo(this.listView.SelectedItem, ScrollToPosition.MakeVisible, false);
  }
}
like image 117
Nestor Avatar answered Sep 09 '25 17:09

Nestor


Don't forget to set also the group. You need to set both the group and the item, see example below:

listView.ScrollTo(item, group, ScrollToPosition.Start, true);
like image 35
Flappy Avatar answered Sep 09 '25 18:09

Flappy