How to make ScrollViewer automatic
-
21-09-2019 - |
Question
I tried to place a TextBlock
inside a ScrollViewer
, and the scroll bar shows up correctly, but I cannot seem to make it automatically scroll down when the Text
property of the TextBlock
is updated. Here's the relevant part of the XAML:
<ScrollViewer>
<TextBlock FontFamily="Consolas"
Text="{Binding Current.Current.Discussion}"
TextWrapping="Wrap" />
</ScrollViewer>
Help would be greatly appreciated, thanks!
Solution
By default, the behavior you get is that the scroll bars will adjust to the amount of text in the textblock, but the viewer will be showing the top of the text. To refresh that properly do this:
scrollViewer.UpdateLayout();
scrollViewer.ScrollToVerticalOffset(txtBlock.ActualHeight);
OTHER TIPS
Listen to the text changed event
textBlock.TextChanged += (o, args) => ScrollTextBoxToBotton();
Actual function to scroll to bottom:
private void ScrollTextBoxToBotton()
{
scrollViewer.UpdateLayout();
scrollViewer.ScrollToVerticalOffset(double.MaxValue);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow