Reputation: 423
In the code, I generate formatted text into a WPF RichTextBox. I use Environment.NewLine to insert line break. Everything looks fine. However, when I copy the contents of a RichTextBox to Clipboard (using RichTextBox context menu) and paste it into Word or WordPad, line breaks disappear. However, if I paste the contents of the clipboard as plain text (e.g. into notepad), the new lines do not disappear. Don't know why this is so?
Update:
// _richTextBox is my object RichTextBox
var doc = _richTextBox.Document;
var paragraph = doc.Blocks.FirstOrDefault() as Paragraph;
if (paragraph == null) return;
var span = new Span();
span.Inlines.Add(new Underline(new Run($"Header: {Environment.NewLine}")));
span.Inlines.Add(new Run("Text content"));
paragraph.Inlines.Add(span);
Upvotes: 0
Views: 564
Reputation: 1409
I am working with RichTextBox which client must be copy-paste with Word application. To my surprise, the Environment.NewLine
did not work. You have to insert paragraph.Inlines.Add( new LineBreak( ) );
Here is complete summary when copy paste from RichTextBox to each application:
The wrong-est \n
not working in any application, unless it is newline aware such as Notepad++
var doc = m_RichTextBox.Document;
doc.Blocks.Clear( );
var p = new Paragraph( );
doc.Blocks.Add( p );
p.Inlines.Add( new Run( "Line1\n" ) );
p.Inlines.Add( new Run( "Line2\n" ) );
p.Inlines.Add( new Run( "Line3\n" ) );
The Environment.NewLine
Notepad says ok, but Word still decided to protest.
/* Same setup code omitted .... */
p.Inlines.Add( new Run( "Line1" + Environment.NewLine ) );
p.Inlines.Add( new Run( "Line2" + Environment.NewLine ) );
p.Inlines.Add( new Run( "Line3" + Environment.NewLine ) );
The correct one
/* Same setup code omitted .... */
p.Inlines.Add( new Run( "Line1" ) );
p.Inlines.Add( new LineBreak( ) );
p.Inlines.Add( new Run( "Line2" ) );
p.Inlines.Add( new LineBreak( ) );
p.Inlines.Add( new Run( "Line3" ) );
p.Inlines.Add( new LineBreak( ) );
Upvotes: 0
Reputation: 423
The solution was simple in the end. I didn't notice that there was a LineBreak
object. If you use LineBreak
instead of \r\n
(Environment.NewLine
), then line break will work in both plain text and formatted text.
Upvotes: 1