问题
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);
来源:https://stackoverflow.com/questions/3485385/how-can-i-calculate-the-verticaloffset-at-which-an-index-would-be-vertically-cen