#382 – Persisting RichTextBox Contents as XAML

You can use the Save method of a TextRange object to save the contents of a RichTextBox control.

In the example below, I enter some formatted text into a RichTextBox and then click the Save button.

Here’s the code that does the save behavior.

        private void Button_Click(object sender, RoutedEventArgs e)
            TextRange allText = new TextRange(rtfMain.Document.ContentStart, rtfMain.Document.ContentEnd);

            FileStream stream = new FileStream(@"D:\AboutMyDog.xaml", FileMode.Create);

            allText.Save(stream, DataFormats.Xaml);

            if (stream != null)

The resulting XAML file consists of an outer Section element that in turn contains multiple Paragraph elements.

        <Run FontStyle="Italic">Kirby</Run>
        <Run> is a </Run>
        <Run FontWeight="Bold">Border Collie</Run>
        <Run FontStyle="Italic">Jack</Run>
        <Run> is a </Run>
        <Run FontWeight="Bold">Jack Russell Terrier</Run>

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: