How to append a TextRange to flow document without losing formatting

858 views Asked by At

I need to add the TextRange to flow document without losing formatting done to it in RichTextBox. I am getting RichTextBox.Text which converts it to string and lose all the formatting but I don't want to loose formatting of text read from RichTextBox.

TextRange t = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
String s = t.Text;

FlowDocument fd = new FlowDocument();
  /*
    this snippet works but looses formatting
    Paragraph p = new Paragraph();
    p.Inlines.Add(s);
    fd.Blocks.Add(p);
  */
fd.Blocks.Add(t); // cannot convert TextRange to Block
1

There are 1 answers

0
slacker On

RichTextBox.Rtf will give you the original content with formatting. So, something like this, perhaps?

FlowDocument flowDoc = new FlowDocument();
TextRange textRange = new TextRange(flowDoc.ContentStart, flowDoc.ContentEnd);

using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(rtb.Rtf)))
{
    textRange.Load(ms, System.Windows.DataFormats.Rtf);
}