#382 – Persisting RichTextBox Contents as XAML
September 8, 2011 Leave a comment
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)
stream.Close();
}
The resulting XAML file consists of an outer Section element that in turn contains multiple Paragraph elements.
<Paragraph>
<Run FontStyle="Italic">Kirby</Run>
<Run> is a </Run>
<Run FontWeight="Bold">Border Collie</Run>
<Run>.</Run>
</Paragraph>
<Paragraph>
<Run FontStyle="Italic">Jack</Run>
<Run> is a </Run>
<Run FontWeight="Bold">Jack Russell Terrier</Run>
<Run>.</Run>
</Paragraph>
