Jose Afonso
Jose Afonso

Reputation: 117

UWP/C# How to scroll text from a TextBox to selected text?

I have a UWP Desktop application with Text to Speech capabilities. In it, I have a TextBox to contain the text that will be executed by the Speech Synthesizer. During execution, the application selects the currently executed phrase. However, since the text is larger than the TextBox, I need to scroll the text so that the executed and selected phrase is visible to the user. How to do this? Any help is most welcome.

Upvotes: 0

Views: 124

Answers (1)

Nico Zhu
Nico Zhu

Reputation: 32785

UWP/C# How to scroll text from a TextBox to selected text?

I'm afraid you can't scroll to specific position wihtin UWP TextBox. It looks does not contains ScrollTo method. However, you could get TextBox's internal ScrollViewer then call ChangeView method to scroll to your wanted position.

For example.

public void ScrollToSp(TextBox control, string text)
{
    var grid = (Grid)VisualTreeHelper.GetChild(control, 0);
    var position = control.Text.Contains(text);
    if (control.Text.Contains(text))
    {
        var index = control.Text.IndexOf(text);
        var rect =  control.GetRectFromCharacterIndex(index, true);

        for (var i = 0; i <= VisualTreeHelper.GetChildrenCount(grid) - 1; i++)
        {
            object obj = VisualTreeHelper.GetChild(grid, i);
            if (!(obj is ScrollViewer)) continue;
            ((ScrollViewer)obj).ChangeView(0.0f, rect.Top, 1.0f);
            break;
        }
    }         
}

Upvotes: 1

Related Questions