如何在 RichTextBox 中以编程方式移动插入位置? [英] How can I move the caretposition programatically in a RichTextBox?

查看:31
本文介绍了如何在 RichTextBox 中以编程方式移动插入位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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;

    }

我不知道如何在代码中移动插入符号,使其出现在插入字符之后,例如,如果原始内容是11"并且我在文本中间插入一个2",我希望插入符号在2"之后.

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".

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

It currently appears as "1x21" (where x is the Caret). Any help would be appreciated

推荐答案

TextPointer 对象指示的位置和 LogicalDirection是不可变的.当内容被编辑或修改时,位置由 TextPointer 指示的相对于周围没有变化文本;而是该位置从内容开头的偏移量相应调整以反映新的相对位置内容.例如,指示位置的 TextPointer给定段落的开头继续指向开头即使内容在之前或之前插入或删除,该段落在段落之后.MSDN

下面的代码在 Button.Click 上插入文本.

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

这篇关于如何在 RichTextBox 中以编程方式移动插入位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆