uwprichtextblock

How to show html format using RichTextBlock


I am currently working on Windows 10 UWP project. I am getting a HTML file from the server and I want show this in UWP app.I want to use RichTextBlock instead of web view.I tried github code here which has used Html2Xaml library but I'm getting error when I try to bind data to RichTextBlock.I found this but it only contains to convert rtf to html

I just simply want to convert html to the RichTextBlock and show the html file in UWP app.Please, someone, suggest how to achieve my requirement with RichTextBlock


Solution

  • The best way to display Html is to use WebView, but if you want to convert it into text that RichTextBlock can display, this may be more complicated.

    Let me briefly explain the idea:

    1. Load Html and turn it into a parseable entity.

    In the nuget package manager, you can find some related Html parsing packages, search Html to download the most popular package.

    2. Parse the Html document and generate the corresponding Block or Inline based on the tag type by recursion

    The recursive method is to check whether the Tag currently being parsed has children, and if so, repeat the parse method.

    3. Write conversion methods for various tags

    RichTextBlock cannot be converted into corresponding styled text according to Html tags, so this needs to be written by ourselves.

    Take <b> ... </b> as an example, this is a bold inline text. You can use this method when converting:

    private static Inline GenerateBold(HtmlNode node)
    {
        if (string.IsNullOrEmpty(node.InnerText.Trim()))
            return null;
        Span s = new Span();
        s.Inlines.Add(new Run() { Text = node.InnerText.Trim(), FontWeight = FontWeights.Bold });
        return s;
    }
    

    The text types supported by RichTextBlock are under the Windows.UI.Xaml.Documents namespace, which are mainly divided into Inline and Block. If you want to see all the text types in this namespace, you can view this document


    Converting Html tags to text types supported by RichTextBlock requires one-to-one conversion. In addition, you may not be able to fully reproduce the effect of CSS on styles in RichTextBlock (this means that you also need to build a CSS parser).

    If you are going to do this great job, I hope my suggestions can help you.

    Best regards.