I am working on adding find and replace functionality to a text editor that I am building and I would like to be able to scroll the textbox so that the selected match is vertically centered on the screen.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can use GetRectFromCharacterIndex to convert from a character index to a rectangle on the screen. This will account for scrolling, so you'll need to add the current VerticalOffset:
var start = textBox.GetRectFromCharacterIndex(textBox.SelectionStart);
var end = textBox.GetRectFromCharacterIndex(textBox.SelectionStart + textBox.SelectionLength);
textBox.ScrollToVerticalOffset((start.Top + end.Bottom - textBox.ViewportHeight) / 2 + textBox.VerticalOffset);
If you have a RichTextBox, you would use TextPointer.GetCharacterRect:
var start = textBox.Selection.Start.GetCharacterRect(LogicalDirection.Forward);
var end = textBox.Selection.End.GetCharacterRect(LogicalDirection.Forward);
textBox.ScrollToVerticalOffset((start.Top + end.Bottom - textBox.ViewportHeight) / 2 + textBox.VerticalOffset);