开发者

Formatting specifc lines of text in WPF RichTextBox

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

Apple

Cheese

Orange

Pear

Chicken

How would I programmatically wit开发者_JS百科h 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?


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!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜