Set RTF text into WPF RichTextBox control

55,163

Solution 1

Do you really have to start with a string?

One method to load RTF is this:

rtfBox.Selection.Load(myStream, DataFormats.Rtf);

You probably should call SelectAll() before that if you want to replace existing text.

So, worst case, you'll have to write your string to a MemoryStream and then feed that stream to the Load() method. Don't forget to Position=0 in between.

But I'm waiting to see somebody to come up with something more elegant.

Solution 2

Create an Extension method

    public static void SetRtf(this RichTextBox rtb, string document)
    {
        var documentBytes = Encoding.UTF8.GetBytes(document);
        using (var reader = new MemoryStream(documentBytes))
        {
            reader.Position = 0;
            rtb.SelectAll();
            rtb.Selection.Load(reader, DataFormats.Rtf);
        }
    }

Then you can do WinForm-esque style

richTextBox1.SetRtf(rtf);

Share:
55,163
Andrija
Author by

Andrija

Software developer

Updated on January 14, 2021

Comments

  • Andrija
    Andrija over 3 years

    I have this RTF text:

    {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Arial;}}
    {\colortbl ;\red0\green0\blue0;\red255\green0\blue0;}
    \viewkind4\uc1\pard\qc\cf1\fs16 test \b bold \cf2\b0\i italic\cf0\i0\fs17 
    \par }
    

    How to set this text into WPF RichTextBox?


    Solution:

    public void SetRTFText(string text)
    {
        MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(text));
        this.mainRTB.Selection.Load(stream, DataFormats.Rtf);
    }
    
  • J. Random Coder
    J. Random Coder over 14 years
    Oh my bad. I missed you where using WPF.
  • Andrija
    Andrija over 14 years
    rtfBox.Selection.Load is what I needed. Thank you :)
  • devios1
    devios1 almost 14 years
    Instead of using the Selection property and worrying about calling SelectAll, you can probably use new TextRange( rtfBox.Document.ContentStart, rtfBox.Document.ContentEnd ) and then call Load on the TextRange (Selection is itself a TextRange).
  • Andrija
    Andrija over 11 years
    You can't use extension method as property.
  • Tom Sirgedas
    Tom Sirgedas over 8 years
    with devios's snippet, this works: TextRange textRange = new TextRange( rtfBox.Document.ContentStart, rtfBox.Document.ContentEnd ); MemoryStream ms = new MemoryStream( ASCIIEncoding.ASCII.GetBytes( rtfText ) ); textRange.Load( ms, DataFormats.Rtf );
  • Marty
    Marty almost 6 years
    That's for Windows Forms, the question specifies WPF.