Search code examples
c#wpfrichtextboxrtf

Why LineHeight gets changed in WPF RichTexBox when reloading its content from a stream


Question: Why the following code changes the default LineHeight in WPF RichTexBox to 0? What would be a proper way to fix the issue?

Xaml for RichTextBox:

<RichTextBox x:Name="rtbTest" AcceptsTab="True" FontFamily="Calibri"/>

Code to reload content of RichTexBox from stream:

TextRange textRange = new TextRange(rtbTest.Document.ContentStart, rtbTest.Document.ContentEnd);
string rtf;
using (var memoryStream = new MemoryStream())
{
    textRange.Save(memoryStream, DataFormats.Rtf);
    rtf = ASCIIEncoding.Default.GetString(memoryStream.ToArray());
}

//rtf = rtf.Replace("abcd", "rstu");

using (MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(rtf)))
{
    rtbTest.SelectAll();
    rtbTest.Selection.Load(stream, DataFormats.Rtf);
}

Screenshot of RichTexBox before running the above code:

enter image description here

Screenshot of RichTexBox AFTER running the above code:

You notice that the default LinHeight got changed to 0.

enter image description here


Solution

  • The DataFormats.Rtf format don't preserve line spacing. Use DataFormats.Xaml instead (doesn’t support images). Or even the DataFormats.XamlPackage: it will save and restore images too.