-1

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?

jps
  • 20,041
  • 15
  • 75
  • 79
R. Warning
  • 77
  • 1
  • 4

1 Answers1

-1

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;
BionicCode
  • 1
  • 4
  • 28
  • 44
  • Unfortunately this does not work. I get the format tags in plain text. – R. Warning Sep 27 '20 at 14:51
  • Unfortunately you did ask for this. What do you expect? Do you want to see the HTML document rendered? – BionicCode Sep 27 '20 at 14:54
  • You must be more specific in your question. If you only want to display content of the HTML tags you must parse it first to replace HTML tags with XAML tags e.g. replace `

    `with ``. If you only have simple text then this is simple, but can get quite complex. You should look for a library on NuGet to convert HTML to XAML (or HTML directly to `FlowDocument`. As explained in my answer `TextRange` cannot convert a HTML string to XAML string. You have to do this. Then `TextRange` can display the XAML string using `DataFormats.Xaml`.

    – BionicCode Sep 27 '20 at 15:11
  • I have not tested this [HtmlToXamlConverter](https://www.nuget.org/packages/HtmlToXamlConverter) library form NuGet, but you should try it (or something similar). Use the result of this converter, which should be a valid XAML string, and assign this result to the `xaml` variable of your posted code snippet. Then it should work. Otherwise add more details to your question. – BionicCode Sep 27 '20 at 15:16