Xamarin.Forms - 如何在 ListView 为 loaded/populated 后滚动到底部?

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

我有一个包含自定义呈现器的 ListView。我希望用户在进入页面时滚动到 ListView 的底部。

由于我的内容已绑定,似乎 OnAppearing 触发得太早了(在我的 ListView 加载之前)。如何在正确的时间触发 ScrollToLast()?

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

    }

ObservableCollection 有一个方法 CollectionChanged,它在添加、删除、更改、移动或刷新整个列表时发生。

所以

  1. 将您的列表指定为 ObservableCollection

  2. 处理 CollectionChanged 方法中的逻辑。

示例代码

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

测试结果