Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate the VerticalOffset at which an index would be vertically centered in the viewing area of a textbox?

Tags:

c#

wpf

textbox

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.

like image 822
Justin Avatar asked Dec 12 '25 07:12

Justin


1 Answers

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);
like image 177
Quartermeister Avatar answered Dec 14 '25 21:12

Quartermeister