Scrolling in .NET MAUI Chat (SfChat)

Scroll to message

You can scroll to a particular message programmatically using the SfChat.ScrollToMessage(Object) method.

<StackLayout>
        <Button x:Name="ScrollTo" Text="Scroll to message" HeightRequest="100" Clicked="ScrollTo_Clicked" />
        <sfChat:SfChat x:Name="sfChat"
            Messages="{Binding Messages}"
            CurrentUser="{Binding CurrentUser}"
            CanAutoScrollToBottom="False"/>
    </StackLayout>
private void ScrollTo_Clicked(object sender, EventArgs e)
    {
        // Scroll to the sixth message in the collection.
        this.sfChat.ScrollToMessage(this.viewModel.Messages[5]);
    }

Auto scroll chat control to bottom when new message is added

By default, the SfChat control is scrolled to the bottom to show the newly added message. If you want to disable this auto scroll, set CanAutoScrollToBottom as false.

<sfChat:SfChat x:Name="sfChat"
                Messages="{Binding Messages}"
                CurrentUser="{Binding CurrentUser}"
                CanAutoScrollToBottom="False"/>

Scrolled event

The SfChat control comes with a built-in Scrolled event that will be fired whenever the chat control is scrolled. You can get the current scroll offset, whether scrolling has reached the top or bottom of the message list in the ChatScrolledEventArgs. You can handle this event to restrict the auto-scroll in chat for newly added messages, if the user had already scrolled up manually and was currently not at the bottom of the chat when the new message was added.

<sfChat:SfChat x:Name="sfChat"
                Messages="{Binding Messages}"
                CurrentUser="{Binding CurrentUser}"
                Scrolled="sfChat_Scrolled"/>
sfChat.Scrolled += sfChat_Scrolled;
    
    private void sfChat_Scrolled(object? sender, ChatScrolledEventArgs e)
    {
        // The chat will not be auto scrolled to the bottom
        // if the user is not currently at the bottom end of the chat at the time of the arrival of the new message
        // but rather already manually scrolled above to read old messages.
        sfChat.CanAutoScrollToBottom = e.IsBottomReached;
    }