Your immediate problem is that you are using TextFormat.Xaml
instead of TextFormat.XamlPackage
.
The property that controls whether or not lines are merged when documents are combined is the Section.HasTrailingParagraphBreakOnPaste
property. This property is only effective when loading or saving the XamlPackage
text format. When using Xaml
text format instead, the property is omitted during Save()
and ignored during Load()
.
So the simple fix is to simply change the Load and Save calls:
tr.Save(ms, DataFormats.XamlPackage);
ms.Seek(0, SeekOrigin.Begin);
tr = new TextRange(target.CaretPosition, target.CaretPosition);
tr.Load(ms, DataFormats.XamlPackage);
Note that this also fixes another problem you would eventually run into: Embedded bitmaps will not be copied properly when using DataFormats.Xaml
because there is nowhere to put the image bits. With DataFormats.XamlPackage
an entire package is built so bitmaps and other package items will come across ok.
Once you make this change you may discover another fact that may or may not be an issue for you: Your sample code uses document.ContentStart
and document.ContentEnd
. If this is your actual code you will discover that any range from document.ContentStart
to document.ContentEnd
necessarily consists of full paragraphs, so copying it will always insert a paragraph break at the end of the insertion. If this is a problem, use something like RichTextBox.Selection
(if this is UI driven) or use TextPointer
to back up ContentEnd
to before the implicit paragraph mark, for example:
var tr = new TextRange(document.ContentStart,
document.ContentEnd.GetInsertionPosition(
LogicalDirection.Backward));