2

Good day!

I try to change part of text to red color.

So, i try to use TextBox, but it not works. So, i read, that RichTextBox can do that:i use this question

But i do not know how to append colored text?

  TextRange rangeOfText1 = new TextRange(tbScriptCode.Document.ContentEnd,    tbScriptCode.Document.ContentEnd);
 rangeOfText1.Text = "Text1 ";
rangeOfText1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
                             rangeOfText1.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

Ok, i get TextRange, but how to append it to RichTextBox?

Can you tell me how to make some part of text to red color? Thank you!

Community
  • 1
  • 1
user2545071
  • 1,408
  • 2
  • 24
  • 46
  • possible duplicate of [How to select text from the RichTextBox and then color it?](http://stackoverflow.com/questions/3707120/how-to-select-text-from-the-richtextbox-and-then-color-it) [accidentally pasted in wrong link! sorry!] – dav_i Feb 19 '15 at 10:49
  • Do you want to edit the text or just display it? – toadflakz Feb 19 '15 at 10:52
  • i want to make simple compile error cheching.So, if i found error of compilation- i want to color error text with red. – user2545071 Feb 19 '15 at 11:05

1 Answers1

5

Starting with your example:

TextRange rangeOfText2 = new TextRange(tbScriptCode.Document.ContentEnd,
    tbScriptCode.Document.ContentEnd);

rangeOfText2.Text = "RED !";

rangeOfText2.ApplyPropertyValue(TextElement.ForegroundProperty,Brushes.Red);
rangeOfText2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

works for me.

Ok, i get TextRange, but how to append it to RichTextBox?

It has already been added with

new TextRange(tbScriptCode.Document.ContentEnd, tbScriptCode.Document.ContentEnd);

What you also can do (I used this myself lately):

var fd = new FlowDocument();

Paragraph paragraph = new Paragraph();

paragraph.Inlines.Add(new Run("normal text and this is in "));
paragraph.Inlines.Add(new Run("red") { Foreground = Brushes.Red });
paragraph.Inlines.Add(new Run(" and this is blue.") { Foreground = Brushes.Blue });

fd.Blocks.Add(paragraph);

tbScriptCode.Document = fd;
Rainer Schaack
  • 1,558
  • 13
  • 16
  • may be new TextRange(tbScriptCode.Document.ContentStart, tbScriptCode.Document.ContentEnd); ? – user2545071 Feb 19 '15 at 11:16
  • 1
    If you use TextRange(tbScriptCode.Document.ContentStart, tbScriptCode.Document.ContentEnd); all existing text will be overwritten. Play a bit with all this stuff. I did this myself some weeks ago, where I searched for a quick way to display some text with specific lines displayed in color. I ended with the FlowDocument solution. There may be better solutions, and the one you came up with seems interesting too. – Rainer Schaack Feb 19 '15 at 11:23