Displaying HTML in Silverlight

In my second post in the series of ripping off other peoples work :-) here’s an updated version of David Anson’s HtmlTextBlock control back from 2007.

This was originally written based on the TextBlock control, but since the TextBlock control was sealed and couldn’t be inherited from, it required a lot of copying properties around. Textblocks also only supports text, so the HyperLink method was not really a hyperlink, and there was no image support, but from what we had available back them, it was a really good solution considering the simplicity (I like simple small implementations).

Since then Silverlight 4 has arrived, and we now have the RichTextBlock control. This supports hyperlinks, images etc, and it is not sealed, so we can pretty easily get around the limitations that the original implementation had. Most of the logic for generating the HTML is the same, but now with proper support for images and real hyperlinks. Again all the credit goes to the original author. I just did some tweaks.

You can download the source with a sample app here: HtmlTextBlock.zip (34.15 kb)

UPDATE: Rewrote the parser approach quite a lot. Now it also supports tables (!) as well as setting fontsize using the H1..H4 tags. With the new parser approach it should be easier to add support for other more complex tags as well.

You can download the source with a sample app here: HtmlTextBlock_v2.zip (34.15 kb)

Comments (4) -

  • Thanks! Very useful enhancement.
  • Another thing, I added TargetName = "_blank" to the HyperLink constructor inside ParseAndSetSpecifiedText() method, so that clicking links doesn't take you out of the app.
  • Morten,

    This comment system is wacky. I added 2 comments last night. After adding the second one, I could still only see the first one. This morning, after clearing browser cookies, I only see my second one. Wierd.

    Anyway, I had a problem with the control where I had its Html property bound, and it was appending html every time the property changed. I fixed it by adding the following to the top of the ParseAndSetText() method:
       this.Selection.Text = "";
    I also had a problem where an exception was being thrown when the DOM parsing routine failed, and I fixed it by changing:
       Xaml = null;
       this.Selection.Text = "";

    Can you explain why Xaml = null doesn't work?
  • Thanks a bunch for the code.  I am trying to render data retrieved from SharePoint and this was a big step forward.  However, the newline code, generated as div tags, are not rendering as a newline in the HTMLbox code.  Are you doing something special with the div tags?  Will it break anything if I write these in?

Pingbacks and trackbacks (2)+

Add comment