converting html to FlowDocument

1.8k views Asked by At

I try to create a wpf core application that uses text imported from a ms Access database. Some of the fields are Access Text fields with text set as RTF text but actually they look like html. like this:

10630981 bla bla bla bla bla   {bla 25-09}

I was thinking to use a FlowDocumentScrollViewer to display this field and a RichTextBox to edit. since I like to work in a MVVM pattern I would need a convertor to convert this 'Html' to a flowdocument and back.

I have been playing for several days no to get this, but did not succeed yet. I feel I am getting near with following Code:

FlowDocument document = new FlowDocument();
string xaml = "<p> The <b> Markup </b> that is to be converted.</p>";
using (MemoryStream msDocument = new MemoryStream((new ASCIIEncoding()).GetBytes(xaml)))
{
   TextRange textRange = new TextRange(document.ContentStart, document.ContentEnd);
   textRange.Load(msDocument, DataFormats.Xaml);
}

But still I get an exception saying XamlParseException: Cannot create unknown type 'p'.

Can somebody give me a push in the right direction?

1

There are 1 answers

4
BionicCode On

You are using the wrong dataformat. Your content is not a valid XAML string. Simply use DataFormats.Text instead.
If you use DataFormats.Xaml the input is expected to be a valid document based on XAML elements like <Run> and <Paragraph>.

You can also assign the string value directly to the TextRange.Text property:

FlowDocument document = new FlowDocument();
string html = "<p> The <b> Markup </b> that is to be converted.</p>";
TextRange textRange = new TextRange(document.ContentStart, document.ContentEnd);
textRange.Text = html;