Reputation: 65
I have a RichTextBox with custom formatting on special bits of text in it. However there is a bug where after a character is inserted, the caret is placed before the newly inserted character instead of after.
This is because for every edit, the code recalculates the content to apply the custom formatting and then sets the CaretPosition like so...
protected override void OnTextChanged(TextChangedEventArgs e)
{
base.OnTextChanged(e);
currentPos = CaretPosition.GetNextInsertionPosition(LogicalDirection.Forward);
// Apply special formatting on the content
Content = GetContentValue();
if (currentPos != null)
CaretPosition = currentPos;
}
I am not sure how to move the caret in code so that it appears AFTER the inserted character e.g if original content is "11" and I insert a "2" in the middle of the text, I would like the Caret to be after the "2".
It currently appears as "1x21" (where x is the Caret). Any help would be appreciated
Upvotes: 2
Views: 1995
Reputation: 9827
The position and LogicalDirection indicated by a TextPointer object are immutable. When content is edited or modified, the position indicated by a TextPointer does not change relative to the surrounding text; rather the offset of that position from the beginning of content is adjusted correspondingly to reflect the new relative position in content. For example, a TextPointer that indicates a position at the beginning of a given paragraph continues to point to the beginning of that paragraph even when content is inserted or deleted before or after the paragraph. MSDN
The code below inserts text on Button.Click
.
private void Button_Click(object sender, RoutedEventArgs e)
{
/* text to insert */
string text = "some text";
/* get start pointer */
TextPointer startPtr = Rtb.Document.ContentStart;
/* get current caret position */
int start = startPtr.GetOffsetToPosition(Rtb.CaretPosition);
/* insert text */
Rtb.CaretPosition.InsertTextInRun(text);
/* update caret position */
Rtb.CaretPosition = startPtr.GetPositionAtOffset((start) + text.Length);
/* update focus */
Rtb.Focus();
}
Upvotes: 3