I want to add some text in a WPF RichTextBox at runtime in a new line. I can do this using:
FlowDocument mcFlowDoc = new FlowDocument();
mcFlowDoc = richTextBox.Document;
Paragraph pr = new Paragraph();
pr.Inlines.Add(status);
mcFlowDoc.Blocks.Add(pr);
StatusText.Document = mcFlowDoc;
But there is too much of a gap between two lines. How can I fix this?
Adding Line Breaks You can do this with a LineBreak inline, added as an XAML element within the text. A new line will be started at the position of this element. If you have configured the text to be justified, the final line before the line break will not be expanded to fill the available width.
XAML attributes of type String may contain any special characters, as long as those are referenced as hex-codes. For example, a simple line break ( \n ) would be represented as 
 , for \r\n you'd use 
 and so on.
The RichTextBox control enables you to display or edit flow content including paragraphs, images, tables, and more. This topic introduces the TextBox class and provides examples of how to use it in both Extensible Application Markup Language (XAML) and C#.
To avoid having to manually set the margin for every paragraph, you can add this to the RichTextBox's XAML:
<RichTextBox>
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
</RichTextBox>
Try pr.Margin = new Thickness(0.0)
to remove the gaps between paragraphs.
According to the documentation, Paragraph spacing is defined by margins, which do not accumulate (no doubling up), so Julien Lebosquain's answer is correct.
MSDN on FlowDocument Paragraph Spacing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With