Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you programatically scroll to the bottom of a TextBox in WinRT?

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?

like image 906
Briggs Avatar asked Jan 18 '13 22:01

Briggs


1 Answers

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);
like image 95
Filip Skakun Avatar answered Oct 14 '22 02:10

Filip Skakun