开发者

WPF RichTextBox - Formatting of typed text

I am applying formatting to selected tokens in a WPF RichTextBox. To do this I get a TextRange that encompasses the token that I would like to highlight. I will then change the color of the text like this:

// Get start and end pointer for token
TextPointer startPointer = run.ContentStart.GetPositionAtOffset(startOffset);
TextPointer endPointer = run.ContentStart.GetPositionAtOffset(endOffset);

// Get 开发者_开发百科text range for token
TextRange textRange = new TextRange(startPointer, endPointer);

// Highlight token
textRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);

This is happening on the TextChanged event of my RichTextBox.

The formatting is applied as expected, but continuing to type text will result in the new text inheriting the formatting that has already been applied to the adjacent word. I would like the formatting of any new text to use the default formatting options defined in the RichTextBox properties. Is this possible?

Alternatively I could highlight all tokens that I don't want be blue with the default formatting options but this feels awkward to me.


Isn't that the standard behavior? If I highlight text in Word, make it bold, move the cursor next to that text and type, the new text becomes bold too. I'd imagine that MS made the rich text box work similarly to the text area in Word.

If you're selecting a token based on matching some criteria, like for syntax highlighting, could you try applying the style to the text after the cursor is 1 character away from the token? For example:

SomeToken |

instead of

SomeToken|

where | is the cursor. The cursor is separated from the token by a space in the first example, so if your program finds SomeToken it'll get the text range from before the S to before the (space). I'd imagine that the style won't be applied to newly entered text then.

I'll admit this is just a guess, and I might have misunderstood your exact situation from your problem description. Some more code might be helpful, particularly the TextChanged event you mention, or the code that creates the text range.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜