Xamarin.Forms - How to scroll to bottom after ListView is loaded/populated?

Viewed 558

I have a ListView which consists of Custom Renderers. I want the user to scroll to the bottom of the ListView on entering the page.

Since my content is binded, it seems that OnAppearing is fired too soon (before my ListView is loaded). How can I fire off ScrollToLast() at the right time?

        protected override void OnAppearing()
        {
            base.OnAppearing();
            this.ItemsListView.ScrollToLast();
        }
    public class CustomListView : ListView
    {
        public CustomListView() : this(ListViewCachingStrategy.RecycleElement)
        {
            ScrollToLast();
        }

        public CustomListView(ListViewCachingStrategy cachingStrategy)
            : base(cachingStrategy)
        {
        }

        public void ScrollToLast()
        {
            try
            {
                if (ItemsSource != null && ItemsSource.Cast<object>().Count() > 0)
                {
                    var lastItem = ItemsSource.Cast<object>().LastOrDefault();
                    if (lastItem != null)
                    {
                        ScrollTo(lastItem, ScrollToPosition.End, false);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }

    }
1 Answers

ObservableCollection has a method CollectionChanged, it occurs when an item is added, removed, changed, moved, or the entire list is refreshed.

So

  1. Specify your list as ObservableCollection .

  2. Handle the logic in CollectionChanged method .

Sample code

   public MainPage()
    {
        InitializeComponent();

        list.CollectionChanged += MyGroupTickets_CollectionChanged;

        for (int i =0; i < 100; i++)
        {
            list.Add(i.ToString());
        }

        listView.ItemsSource = list;

    }

    private void MyGroupTickets_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        listView.ScrollTo(list[list.Count - 1], ScrollToPosition.End, false);
    }

Test result

enter image description here

Related