tags:

views:

28

answers:

1

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  A: 

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);
Quartermeister
Any suggestion on the best way to implement this using MVVM?
Justin
@Justin: The rectangles and offsets belong to the View, so it's a question of how to trigger the scrolling and how to identify the text range. You could have your ViewModel raise an event with the range to highlight, and have a handler in the View that scrolls that range to the center. Or, you could create attached properties for the selection range in the View that scroll the target when they change, and then you could bind them to properties for the range in the ViewModel. It depends partly on how you're modeling find and replace in your ViewModel.
Quartermeister