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

Jus*_*tin 2 c# wpf textbox

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

Qua*_*ter 5

您可以使用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);
Run Code Online (Sandbox Code Playgroud)

如果您有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);
Run Code Online (Sandbox Code Playgroud)