Best Way to Scroll to End of ScrollViewer

2020-06-09 07:58发布

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?

9条回答
Emotional °昔
2楼-- · 2020-06-09 08:21

For Windows Phone 8.1 I use this:

MyScrollViewer.ChangeView(0.0f, double.MaxValue, 1.0f);
查看更多
3楼-- · 2020-06-09 08:26

For Windows Phone 8.0, you can use

MyScrollViewer.ScrollToVerticalOffset(MyScrollViewer.ExtentHeight - MyScrollViewer.ViewportHeight);

Please also refer to http://msdn.microsoft.com/en-us/library/windows/apps/system.windows.controls.scrollviewer.verticaloffset(v=vs.105).aspx

查看更多
神经病院院长
4楼-- · 2020-06-09 08:30

If you are working with .NET 3.0 or later, you can use ScrollViewer.ScrollToBottom().

MSDN doc: http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.scrolltobottom(v=vs.110).aspx

查看更多
登录 后发表回答