Raven Raven - 1 month ago 23
C# Question

How to set ListView to Start showing the last Item instead in Xamarin Forms?

I have a list of Items being handled by the ListView. By default, the ListView shows the from start to bottom (scrolling).

How do I set the ListView to start at the bottom instead?

Usage:
Chat Messages View - Wherein I need to show the last message of the chat and scroll to that.

Answer

You can use ScrollTo in a ListView to scroll to a any position you set. You need to overwrite the OnAppearing method. This is an example for scrolling to the end of the ListView ViewModel.Messages:

protected override void OnAppearing()
    {
        base.OnAppearing();

        ViewModel.RefreshScrollDown = () => {
            if (ViewModel.Messages.Count > 0) {
                Device.BeginInvokeOnMainThread (() => {

                    ListViewMessages.ScrollTo (ViewModel.Messages [ViewModel.Messages.Count - 1], ScrollToPosition.End, true);
                });
            }
        };
    }

Then just call RefreshScrollDown (which is System.Action) every time you need to scroll down, e.g. when you recieve a new message or when you load the chats.

Note: This works for iOS and Android, but apparently not for UWP. I haven't found a solution for UWP yet.