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 + "rn";
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);
链接地址: http://www.djcxy.com/p/68658.html

上一篇: 具有核心部分的命名空间包?

下一篇: 你如何以编程方式滚动到WinRT中TextBox的底部?