Where is ScrollToCaret in a TextBox in WPF?

2019-02-25 06:36发布

I'm unable to find that function. Basically I have a multiline text box and when I perform a search, I highlight the result. But if the result is not within view, I would have to manually scroll down until I find the highlighted result, which beats the purpose of the "Find" functionality.

I don't want to use RichTextBox because I've encountered some performance issues with it.

标签: c# wpf textbox
3条回答
【Aperson】
2楼-- · 2019-02-25 06:49

You could use GetLineIndexFromCharacterIndex in combination with ScrollToLine:

var selectionStart = x;
var selectionLength = y;
textBox.Select(selectionStart, selectionLength);
textBox.ScrollToLine(textBox.GetLineIndexFromCharacterIndex(textBox.SelectionStart));
查看更多
来,给爷笑一个
3楼-- · 2019-02-25 07:05

ScrollToLine was not accurate enough for me. My text box had wrapping enabled, so Line Index was not reliable. Instead I used this:

textBox.CaretIndex = selectionStart;
textBox.ScrollToEnd();
textBox.Select(selectionStart, selectionLength);

Basically, ScrollToEnd performs a scroll to caret.

查看更多
倾城 Initia
4楼-- · 2019-02-25 07:07

I found a slightly easier way.

textbox.ScrollToLine(textbox.LineCount - 1);

查看更多
登录 后发表回答