Sam
Sam

Reputation: 30388

Xamarin CollectionView scroll to bottom at initialization

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.

Upvotes: 1

Views: 2127

Answers (2)

Andrew
Andrew

Reputation: 1438

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

Upvotes: 3

Anton
Anton

Reputation: 41

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

Upvotes: 1

Related Questions