如何以编程方式在 RichTextBox 中移动插入符位置?

How can I move the caretposition programatically in a RichTextBox?

我有一个 RichTextBox,其中的特殊文本位具有自定义格式。但是存在一个错误,即插入字符后,插入符号位于新插入字符之前而不是之后。

这是因为对于每次编辑,代码都会重新计算内容以应用自定义格式,然后像这样设置 CaretPosition...

 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;

    }

我不确定如何在代码中移动插入符,使其出现在插入的字符之后,例如,如果原始内容是“11”,而我在文本中间插入一个“2”,我想要插入符号在“2”之后。

它目前显示为“1x21”(其中 x 是插入符)。任何帮助将不胜感激

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

下面的代码在 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();
    }