Paragraph formatting in a WPF RichTextBox?
- by David Veeneman
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!