Home > Net >  Xamarin CollectionView scroll to bottom at initialization
Xamarin CollectionView scroll to bottom at initialization

Time:05-22

How do I make sure that a CollectionView displays the last item i.e. the bottom one, from the start without the user having to scroll all the way down.

I use this in a chat UI that I created and want to make sure that the latest messages are in user's view right from the beginning and the user can always scroll up to see older messages.

CodePudding user response:

Set a command in your VM that you can execute when the data is loaded or changed and listen for it in the view and do the scrolling there.

In your VM:

public Command CollectionUpdatedCommand { get; set; }

And then, once the collection changes, whenever you need to fire it:

CollectionUpdatedCommand?.Execute(null);

In your view, set the scroll code to execute when the command is executed:

viewModel.CollectionUpdatedCommand = new Command(() =>
{
    Device.BeginInvokeOnMainThread(() => {
        MessageList.ScrollTo(viewModel.Messages.Last(), null, ScrollToPosition.End, true);
    });
});

CodePudding user response:

You can do something like this along the OnAppearing() :

Device.BeginInvokeOnMainThread(() => {
  MessageList.ScrollTo(viewModel.Messages.Last(), null, ScrollToPosition.End, true);
});`  

Where MessageList - it's your CollectionView
and
viewModel.Messages - it's your Messages collection for this CollectionView e.g. ObservableCollection

  • Related