I am using TextRanges in a WPF RichTextBox and I want to change the font color of a TextRange, but that if then it is written text next to it, it has the original color. For exmaple, I have a RichTextBox called richTextBox with font color black, and I use this code:
TextPointer start = richTextBox.Document.ContentStart;
TextPointer end = richTextBox.Document.ContentEnd;
new TextRange(start, end).ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
I want that if, after executing this code, someone adds text to the richTextBox, it is written in black, not in blue. Is there any way to do this? Thank you!
I don't think you can set it directly so that the next caracter would be in a different color. (Someone please correct me if you know how).
But what you could do is subscribe to the TextChangedEvent of your RichTextBox and apply the new foreground color when the user add some text at the end.
The tricky part however is to detect how much was changed so you can apply the new foreground to this part only and to know if the changes made where done at the end of the text.
Where you execute the code for setting the foreground to blue:
Variables and new method added:
Source for the very useful regex expression https://stackoverflow.com/a/1982317/13448212
In the textChanged event, you have to check if the change is due to the user adding text, then determine if the changes were made at the end of the text:
Documentation for e.Changes: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.textchangedeventargs.changes?view=netcore-3.1#System_Windows_Controls_TextChangedEventArgs_Changes