Search code examples
c#wpfrichtextboxtextrange

How do I set a property to the last typed symbol in richtextbox in wpf?


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?


Solution

  • To get the latest TextRange, simply use this code:

    private TextRange LatestSymbol
    {
        get
        {
            var previous = InputString.CaretPosition.GetPositionAtOffset(-1);
    
            if (previous != null)
            {    
                 return new TextRange(
                          previous,
                          InputString.CaretPosition
                        );
                    }
                return null;
            }
        }
    }
    

    The thing here is, that CaretPosition.GetPositionAtOffset(-1) returns the position that is 1 symbol behind the currentPosition.

    And this works well and without any bugs.