I remembered that I completely solved this problem, so I looked at my old code and found it. All the changes in caret position will be caught if you override the virtual method
TextBox.OnSelectionChanged
. You can also handle the event
SelectionChanged
, of course. I prefer to subclass the control and advice you to do so, as you are implemented a bit more advanced features. For a bonus, I'll show you how to calculate caret position in terms of line/column. Assuming you subclass the text box, it will look like this:
partial class MyTextBox : TextBox {
void InquireCaretPosition(out Position line, out Position column) {
line = 0; column = 0;
int caret = this.CaretIndex;
int iLine = this.GetLineIndexFromCharacterIndex(caret);
if (iLine < 0) iLine = 0;
line = iLine;
int firstChar = this.GetCharacterIndexFromLineIndex(iLine);
if (firstChar 0) firstChar = 0;
column = caret - firstChar;
}
protected override void OnSelectionChanged(RoutedEventArgs e) {
base.OnSelectionChanged(e);
ShowPosition();
}
void ShowPosition() {
int line, column;
InquireCaretPosition(out line, out column);
}
}
Don't forget to show position on some other events, such as when your text box is shown, etc.
Good luck,
—SA