Paragraph formatting in a WPF RichTextBox?

Posted by David Veeneman on Stack Overflow See other posts from Stack Overflow or by David Veeneman
Published on 2010-03-22T16:13:09Z Indexed on 2010/03/22 16:31 UTC
Read the original article Hit count: 1283

Filed under:
|
|

I need to apply paragraph formatting to a selection in a rich text box. My RTB will behave the same way as the rich text boxes on StackOverflow--the user can type text into the RTB, but they can also enter code blocks. The RTB will apply very simple formatting to the code block--it will change the font and apply a background color to the entire block, similar to what you see in the code block below.

Changing the font is pretty straightforward:

var textRange = new TextRange(rtb.Selection.Start, rtb.Selection.End);
textRange.ApplyPropertyValue(TextElement.FontFamilyProperty, "Consolas");
textRange.ApplyPropertyValue(TextElement.FontSizeProperty, 10D );

Now I need to apply some paragraph-level formatting. I need to set the paragraph margin to 0, so I don't get a blank line between code lines, and I need to set the paragraph background color. Here's my problem: I can't figure out how to get the paragraph elements from the selection, so that I can apply formatting.

Any suggestions? An example of how to apply the Margin and Background properties would be incredibly helpful. Thanks!

© Stack Overflow or respective owner

Related posts about wpf

Related posts about flowdocument