Search code examples
c#xamlscrollvieweravaloniauiavalonia

How to scroll to the new element of a ScrollViewer automatically in Avalonia?


I have a chat app on Avaloni UI. Messages are displayed in the ScrollViewer. I need to scroll the list of messages to a new message when I receive or send a message.


Solution

  • You can use the ScrollViewer.ScrollToEnd() method.

    Here is an usage example from an app of mine:

    public class ClientPage : UserControl
    {
        private ScrollViewer messageLogScrollViewer;
    
        public ClientPage()
        {
            this.InitializeComponent();
            messageLogScrollViewer = this.FindControl<ScrollViewer>("MessageLogScrollViewer");
        }
    
        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }
    
        public void ScrollTextToEnd()
        {
            messageLogScrollViewer.ScrollToEnd();
        }
    }
    

    Depending on your specific use case you might instead need to use the ScrollViewer.LineDown() method or any other of the provided methods.

    Additionally you can also set the Offset yourself.