Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Way to Scroll to End of ScrollViewer

Currently, the only way I have gotten my code to auto scroll to the end when I add a new item is the following:

XAML:

<ScrollViewer x:Name="chatViewScroller" HorizontalAlignment="Left" Height="201" Margin="0,32,0,0" VerticalAlignment="Top" Width="475" Background="#7FFFFFFF">
    <StackPanel x:Name="chatViewContent" />
</ScrollViewer>

Code:

                chatViewContent.Children.Add(
                    new TextBlock() {
                        Text = text,
                        FontSize = 18,
                        TextWrapping = Windows.UI.Xaml.TextWrapping.Wrap,
                        Margin = new Thickness(10, 3, 10, 0),
                        Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(
                            isServerMessage ? Windows.UI.Colors.Purple : Windows.UI.Colors.Black)
                    });
                await Task.Delay(10);
                chatViewScroller.ScrollToVerticalOffset(chatViewScroller.ScrollableHeight);

Is this the accepted way of doing it? Do I have to wait for some random period of time?

like image 662
Nick Banks Avatar asked Jun 23 '12 17:06

Nick Banks


3 Answers

Using ActualHeight did not work for me (I have yet to figure out why) - but using ScrollableHeight like this did the the trick:

// adding item to ItemsControl...
// ...
_scrollViewer.UpdateLayout();
_scrollViewer.ScrollToVerticalOffset(_scrollViewer.ScrollableHeight);
like image 50
RiaanDP Avatar answered Nov 12 '22 21:11

RiaanDP


For Windows Phone 8.1 I use this:

MyScrollViewer.ChangeView(0.0f, double.MaxValue, 1.0f);
like image 15
A.J.Bauer Avatar answered Nov 12 '22 20:11

A.J.Bauer


In my opinion best option is to inherit from ScrollViewer in following way:

public partial class AutoScrollViewer
{        
    public AutoScrollViewer()
    {
        InitializeComponent();
        this.SizeChanged += (sender, args) => this.ScrollToBottom();
    }
}

and XAML

<ScrollViewer x:Class="AutoScrollViewer"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</ScrollViewer>

Then you can use directly in XAML the new class without additional code behind which is usefull especailly when you have "pure" MVVM code.

like image 3
Jacek Plesnar Avatar answered Nov 12 '22 21:11

Jacek Plesnar