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?
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);
For Windows Phone 8.1 I use this:
MyScrollViewer.ChangeView(0.0f, double.MaxValue, 1.0f);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With