如何计算在文本框的查看区域中索引垂直居中的VerticalOffset?

我正在努力将查找和替换function添加到我正在构建的文本编辑器中,并且我希望能够滚动文本框,以便所选匹配在屏幕上垂直居中。

您可以使用GetRectFromCharacterIndex将字符索引转换为屏幕上的矩形。 这将考虑滚动,因此您需要添加当前的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); 

如果您有RichTextBox,则可以使用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);