3

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());
            }
        }

    }
TJP
  • 43
  • 4
  • It doesn't matter that it is binded. You can invoke the method in the binded value's setter. Another case is that you can track property changed on your value, this way you can invoke it via an event handler. – Mihail Duchev Jun 08 '20 at 08:56

1 Answers1

3

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

ColeX
  • 14,062
  • 5
  • 43
  • 240