'WPF writing html to a rich text box

I am working on a WPF Windows application using C# code. This is an application I inherited. I only have limited experience using WPF. I have a Rich Text Box control which is used to build an Email using html. There is code to read the Rich Text Box contents and store the results as html in a database. This code is working. I need to write the reverse that is writing the html to the rich text box so it appears as text.

Below is the code I have to read the rich text box.

 TextRange xaml = new TextRange(EmailBodyRichTextBox.Document.ContentStart, EmailBodyRichTextBox.Document.ContentEnd);
            MemoryStream ms = new MemoryStream();
            xaml.Save(ms, DataFormats.Xaml);
            string xamlString = ASCIIEncoding.Default.GetString(ms.ToArray());

            string html = HTMLConverter.HtmlFromXamlConverter.ConvertXamlToHtml("<FlowDocument>" + xamlString + "</FlowDocument>");

            html = HttpUtility.HtmlEncode(html);


Solution 1:[1]

From the code you post above , it seems , you are saving the text in the rich text box to xaml, and then translate the xaml to HTML.

if you want to reverse, then translate your HTML to xaml and then load it to the rich text box.

Solution 2:[2]

To save the RichTextBox's content to a regular string that you can save in a database:

string formattedEmail = XamlWriter.Save(EmailBodyRichTextBox.Document);

To reload the RichTextBox from the string:

EmailBodyRichTextBox.Document = XamlReader.Parse(formattedEmail);

If you only want to store the emails in the database and then reload them to RichTextBoxes, there is no point in converting to HTML, it can only introduce conversion format mismatches.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Johnny
Solution 2 SemMike