WebView the most convenient approach, lest you implement an entire browser rendering engine to capture everyone’s use case.
WebView isn’t alway the right control, since it has significant overhead and doesn’t play well inside of
Pivot or any other containers allowing gestures. In my case, I wanted to display comments from Disqus in a
ListView while supporting its limited HTML markup. There are numerous other web services that use HTML for rendering markup and nothing else, and was my motivation for creating UWP-RichTextControls.
Right now there are two controls:
We’ll go over each below.
Under the hood, AngleSharp is used for parsing the HTML and does an excellent job, even with inconsistent markup. After parsing an HTML document, each node is converted to either a
Inline, depending on the type and structure of the markup. This control requires valid nesting, so putting a block-level
<h1> inside of a
<p> tag won’t do anything special (although you could customize it to do so!).
This is also limited in scope to just HTML (no styles or js), so if you’re looking for something more robust a
WebView control might still be the better option.
Add a reference to the
RichTextControls namespace in your XAML file.
Now you can use the control in your xaml
If you’re trying to customize how some tags render, or support other HTML tags, you may subclass
HtmlXamlGenerator and pass it into the control. Here’s an example we use at Disqus to support a custom
<spoiler> html tag.
Now you can pass it to the control:
If your tag supports HTML inlines as children, you can also use the
AddInlineChildren() methods. This is an example of how we generate Inlines for
This will create a new
Span and call
GenerateInlineForNode() to generate inlines for each child node (including plain text) until there are none left.
I based this off of the nice example from Adnan Umer’s blog post Developing lexer for Syntax Highlighting, which provided the Python lexer. I added lexers for the rest of the languages, but given my limited experience with some of them, could be of varying quality. If you feel something can be improved, please do contribute!
This is also used by the
HtmlRichTextBlock control if you include the Highlight.js class syntax in your HTML:
I’ll continue to develop this library further when dictated by needs of the Disqus UWP app. For now I need to:
- Add more properties for customizing how individual HTML tags render
- Introduce more test coverage, especially on
- Check performance and optimize if needed
This project will be on NuGet once I have done that.
In the future I want to create extension methods for
RichEditBox to render HTML, and convert the rich markup back to HTML. This would allow a user to use native rich editing and import/export back to HTML for a web service.
If you’re interested in using this for your project, get in touch and we can try to make this project better.