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

北战南征 提交于 2020-01-13 19:12:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!