spiderman
spiderman

Reputation: 1585

Change color in RichTextBox

I am using this simple example from MSDN to insert lines in a RichTextBox.

FlowDocument myFlowDoc = new FlowDocument();

Run myRun = new Run("This is flow content and you can ");
Bold myBold = new Bold(new Run("edit me!"));

Paragraph myParagraph = new Paragraph();
myParagraph.Inlines.Add(myRun);
myParagraph.Inlines.Add(myBold);

myFlowDoc.Blocks.Add(myParagraph);

RichTextBox myRichTextBox = new RichTextBox();
myRichTextBox.Document = myFlowDoc;

I want to apply a chosed color to the lines of text, but how to do it?

The Paragraph or Run classes doesn't have any direct method to change the color.

EDIT

I don't want to use all the awkard SelectionStart, SelectionEnd stuff as posted on the linked post!.

My case is different and is much more simple: the solution posted from mm8 explains it and is very elegant. One single line of code and that is!

Please see the answer!

Upvotes: 1

Views: 114

Answers (2)

mm8
mm8

Reputation: 169200

The Paragraph or Run classes doesn't have any direct method to change the color.

The Run class inherits from TextElement and this class has a Foreground property that you can set to a Brush:

Run myRun = new Run("This is flow content and you can ") { Foreground = Brushes.Red };
Bold myBold = new Bold(new Run("edit me!") { Foreground = Brushes.Gray });

Upvotes: 6

Nhan Phan
Nhan Phan

Reputation: 1302

You can get/set text color via Foreground property of the rich text box. As bellow example, I changed the text color of rich text box to blue:

myRichTextBox.Foreground = Brushes.Blue;

Happy coding!

Upvotes: 2

Related Questions