I am writing a simple application for WinRT and I am having trouble figuring out a way to automatically scroll to the bottom of a TextBox in my code. I am writing log information to a TextBox and would like it to scroll so that the newest entries are visible in the box, but nothing seems to work. Below are a few things I've tried:
Place the TextBox in a ScrollViewer:
this.txtLog.Text = this.txtLog.Text + line + "\r\n";
ScrollToVerticallOffset(scrollView.ScrollableHeight);
Select the last data in the TextBox:
this.txtLog.Select(this.txtLog.Text.Length, 0);
But nothing I do actually causes the displayed text to scroll so that the bottom data is visible.
Does anyone have any ideas?
This works:
XAML
<TextBox
x:Name="tb"....
C#
var sv = tb.GetFirstDescendantOfType<ScrollViewer>();
sv.ScrollToVerticalOffsetWithAnimation(sv.ExtentHeight - sv.ViewportHeight);
That uses Winrt XAML Toolkit.
Non-toolkit way:
Func<DependencyObject, ScrollViewer> getFirstDescendantScrollViewer = null;
getFirstDescendantScrollViewer =
parent =>
{
var c = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < c; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
var sv = child as ScrollViewer;
if (sv != null)
return sv;
sv = getFirstDescendantScrollViewer(child);
if (sv != null)
return sv;
}
return null;
};
var tbsv = getFirstDescendantScrollViewer(tb);
tbsv.ScrollToVerticalOffset(tbsv.ScrollableHeight);
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