Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding text in a new line in WPF RichTextBox at runtime

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?

like image 872
Jeevan Bhatt Avatar asked Jun 20 '10 09:06

Jeevan Bhatt


People also ask

How do I create a new line in Textblock WPF?

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.

How do you insert a line break in XAML?

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.

What is RichTextBox WPF?

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#.


3 Answers

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>
like image 142
Merad Avatar answered Sep 19 '22 22:09

Merad


Try pr.Margin = new Thickness(0.0) to remove the gaps between paragraphs.

like image 42
Julien Lebosquain Avatar answered Sep 16 '22 22:09

Julien Lebosquain


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

like image 33
Ian Gilham Avatar answered Sep 16 '22 22:09

Ian Gilham