0

I want to set some background or foreground properties to the latest symbol in RichTextBox.

I tried getting the latest textrange by saving the caret position before the input and then getting the textrange like that: new TextRange(previousCaret, currentCaret).

However this is a bug-prone decision, because you can actually get 2 or more last symbols in case if the caret position wasn't updated in time (for example, you are typing very quickly and pressing the buttons at the same time)

Now, maybe I don't even have to get the latest symbol's TextRange? Are there other ways, like some built-in methods?

So, how do I change the latest symbol's properties properly?

4

1 回答 1

0

要获取最新的 TextRange,只需使用以下代码:

private TextRange LatestSymbol
{
    get
    {
        var previous = InputString.CaretPosition.GetPositionAtOffset(-1);

        if (previous != null)
        {    
             return new TextRange(
                      previous,
                      InputString.CaretPosition
                    );
                }
            return null;
        }
    }
}

这里的问题是, CaretPosition.GetPositionAtOffset(-1) 返回当前位置后面 1 个符号的位置。

这很好用,没有任何错误。

于 2019-03-04T21:05:28.220 回答