How can I move the caretposition programatically in a RichTextBox?

ε祈祈猫儿з 提交于 2019-12-08 07:00:27

问题


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


回答1:


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();
    }


来源:https://stackoverflow.com/questions/39963927/how-can-i-move-the-caretposition-programatically-in-a-richtextbox

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