Question

In a WPF .NET 4.0 RichTextBox with the following text:

Apple

Cheese

Orange

Pear

Chicken

How would I programmatically with C#, (not with XAML markup), bold all lines that start with the character "C"?

More generally, how do you get a reference to a given line of text from a RichTextBox and then apply some formatting to it?

Was it helpful?

Solution

Well that was trickier than I expected but I think the code below does it:

        foreach (var paragraph in richTextBox1.Document.Blocks)
        {
            var text = new TextRange(paragraph.ContentStart,
                           paragraph.ContentEnd).Text;

            paragraph.FontWeight = text.StartsWith("C") ?
                           FontWeights.Bold : FontWeights.Normal;
        }

Basically, the RichTextBox holds its content in a FlowDocument (accessed through the Document property), which in turn has a collection of Blocks containing each Paragraph. Actually, each item in the Blocks collection can be anything derived from the abstract class Block...but I'm assuming if you only ever add simple text to your RichTextBox then they'll always just be Paragraphs. See here for a better explanation!

The trickiest part is that to get the text out of the paragraph you need to use the TextRange class...but the good news is that, once we have the text, the Paragraph has simple properties on it for setting the font weight, etc!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top