Paragraph formatting in WPF RichTextBox?

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

Changing the font is quite simple:

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 formatting at the paragraph level. I need to set the border of the paragraph to 0, so I do not get an empty line between the lines of code, and I need to set the background color of the paragraph. Here's my problem: I can't figure out how to get paragraph elements from the selection so that I can apply formatting.

Any suggestions? An example of using the Margin and Background properties will be incredibly useful. Thank!

+3
source share
1 answer

Oh, that was easy. I went through the answer with a bit of research:

var textRange = new TextRange(TextBox.Selection.Start, TextBox.Selection.End);
textRange.ApplyPropertyValue(TextElement.FontFamilyProperty, "Consolas");
textRange.ApplyPropertyValue(TextElement.FontSizeProperty, 10D );
textRange.ApplyPropertyValue(Paragraph.MarginProperty, new Thickness(0));
textRange.ApplyPropertyValue(Paragraph.BackgroundProperty, "LightSteelBlue");

The only limitation is that the selection still applies only to the text, and not to the right side of the control. I will leave this question open for a couple of days; if someone tells me how to expand the background to the right edge of the control, I will accept my answer to this question.

+3
source

Source: https://habr.com/ru/post/1738056/


All Articles