How do you programatically scroll to the bottom of

2019-06-17 06:32发布

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?

1条回答
迷人小祖宗
2楼-- · 2019-06-17 07:26

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);
查看更多
登录 后发表回答