Click here to Skip to main content
15,867,308 members
Articles / Desktop Programming / WPF

WPF HTML Supported TextBlock

Rate me:
Please Sign up or sign in to vote.
4.36/5 (9 votes)
7 Feb 2009LGPL32 min read 172.1K   1.1K   35   27
This article describes HtmlTextBlock which is a WPF TextBlock that can parse a limited set of HTML tags and display them.
htmltextblock/mainscreen.jpg

Introduction

This article describes HtmlTextBlock which is a WPF TextBlock that can parse a limited set of HTML tags and display them.

Background

I was working on a custom progress dialog, which contains a Header, Message, Progress and some action buttons.

To make it look better, I want the message to support some text format, and I want it to be changeable at runtime, but it seems impossible using TextBlock.

htmltextblock/background.jpg

I then Googled how to use HTML in WPF but most solutions told me to use WebBrowser, which is a bit of an overkill for my purpose.

Then I remembered an abandoned project I wrote a few years ago (mostly because I moved to WPF) , which tried to recreate FlowDocument in .NET 2, and load HTML document (my main purpose, the component was named QzMiniHtml2).

Surprisingly, with very few modifications (mostly using import), this .NET 2 project worked nicely with WPF, just as you can see above.

Because of this, the original project is included as well.

How to Use?

The control is similar to TextBlock except you set the HTML property instead of Text.
Remember to use [ ] bracket instead of < >.

XML
<Window x:Class="HtmlTextBlockTestProj.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:uc="http://www.quickzip.org/UserControls"
    Title="HtmlTextBlockTest" Height="250" Width="450">
    <DockPanel>
        <uc:HtmlTextBlock Html="{Binding Text, ElementName=tb}"
                 DockPanel.Dock="Top" Loaded="HtmlTextBlock_Loaded" />
        <TextBlock Text="[b] [i] [u] [a href=xx] [br] supported."
                 DockPanel.Dock="Bottom" />
        <TextBox TextWrapping="Wrap" AcceptsReturn="True"
                  VerticalScrollBarVisibility="Visible"
                  x:Name="tb"
        Text="The [i][u]quick brown fox[/i][/u] jumps over the [b]lazy dog[/b]" />
    </DockPanel>
</Window>         

How It Works?

The component actually included an HTML parsing engine inside, which translates HTML string to WPF's Bold, Italic, Underline, Hyperlink, LineBreak Inline (more can be added in future, you can do it yourself easily, see below.)

The conversion part is simple.

C#
1) private Inline UpdateElement(HtmlTag aTag)
2) {
3)   Inline retVal = null;

4)   switch (aTag.Name)
5)   {
6)     case "text" :
7)       retVal = new Run(aTag["value"]);
8)       if (currentState.Bold) retVal = new Bold(retVal);
9)       if (currentState.Italic) retVal = new Italic(retVal);
0)       if (currentState.Underline) retVal = new Underline(retVal);
A)       break;
B)     case "br" :
C)       retVal = new LineBreak();
D)       break;
E)   }

F)   if (currentState.HyperLink != null && currentState.HyperLink != "")
G)   {
H)     Hyperlink link = new Hyperlink(retVal);
I)     link.NavigateUri = new Uri(currentState.HyperLink);
J)     retVal = link;
K)   }
L)    return retVal;
M) }         

First, please note that:

  • The input (aTag) is a Text or LineBreak(br), if the tag is a text, Tag["value"] is the text it holds.
    Bold, Italic, etc. can also be represented by HtmlTag, but they won't be executed here.
  • CurrentState holds the style affecting the TextTag, etc.

So if the tag is text (line 6):

  • it will generate a Run (which can contain format or unformat text, and unformat in this case) (line 7)
  • if it's bold, italic and underline, it will construct them, and using last Inline (Abstract class, Run, Bold, etc. inherited from it), so it contains the property.

When the Inline is returned (Line L):

  • It will be added to your HtmlTextBlock.Inlines collection.

History

  • 08-02-09 Initial version

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Founder
Hong Kong Hong Kong

Comments and Discussions

 
QuestionEscape character for [ and ]. Pin
User 136423586-Aug-18 5:54
User 136423586-Aug-18 5:54 
QuestionChanging mouse on hover? Pin
Andy Cartwright30-Aug-15 9:53
Andy Cartwright30-Aug-15 9:53 
QuestionHow to handle click Event Pin
Member 1118186626-Oct-14 16:07
Member 1118186626-Oct-14 16:07 
AnswerRe: How to handle click Event Pin
Leung Yat Chun26-Oct-14 23:59
Leung Yat Chun26-Oct-14 23:59 
GeneralRe: How to handle click Event Pin
Member 1168374112-May-15 2:26
Member 1168374112-May-15 2:26 
GeneralMy vote of 1 Pin
starsky_chen6-Jan-13 5:16
starsky_chen6-Jan-13 5:16 
QuestionUnable to download the attached sample Pin
ksvimalraj28-Jul-11 17:28
ksvimalraj28-Jul-11 17:28 
AnswerRe: Unable to download the attached sample Pin
Leung Yat Chun29-Jul-11 3:52
Leung Yat Chun29-Jul-11 3:52 
GeneralSmall bug Pin
ArlenFeldman25-Mar-11 14:55
ArlenFeldman25-Mar-11 14:55 
GeneralThis is ... Pin
Xmen Real 2-Jul-10 5:25
professional Xmen Real 2-Jul-10 5:25 
GeneralSaving me a lot of time! Pin
MikePelton12-Dec-09 5:01
MikePelton12-Dec-09 5:01 
Generalimage in text block Pin
pathurun8-Sep-09 21:35
pathurun8-Sep-09 21:35 
GeneralRe: image in text block Pin
Leung Yat Chun15-Sep-09 0:56
Leung Yat Chun15-Sep-09 0:56 
GeneralDoes not work if Html Text is assigned to the HtmlTextBlock during Binding Pin
azamsharp1-Jul-09 10:09
azamsharp1-Jul-09 10:09 
GeneralRe: Does not work if Html Text is assigned to the HtmlTextBlock during Binding Pin
Leung Yat Chun2-Jul-09 7:06
Leung Yat Chun2-Jul-09 7:06 
Generalextensions Pin
Lee_Nover20-Mar-09 15:11
Lee_Nover20-Mar-09 15:11 
GeneralRe: extensions Pin
Leung Yat Chun20-Mar-09 20:35
Leung Yat Chun20-Mar-09 20:35 
Greetings

thanks, yes, I have implemented these as well.

I am currently having trouble implementing [sub] and [sup] tag, I created a implementation for that but it seems doesn't work, the following is my code :

<br />
retVal = new Run(aTag["value"]);<br />
<br />
if (currentState.SubScript) <br />
  retVal.SetValue(Typography.VariantsProperty, FontVariants.Subscript);<br />
if (currentState.SuperScript) <br />
  retVal.SetValue(Typography.VariantsProperty, FontVariants.Superscript);                        <br />
						if (currentState.Bold) retVal = new Bold(retVal);<br />
						if (currentState.Italic) retVal = new Italic(retVal);<br />
						if (currentState.Underline) retVal = new Underline(retVal);                        <br />
                        <br />
                        if (currentState.Foreground.HasValue)<br />
                            retVal.Foreground = new SolidColorBrush(currentState.Foreground.Value);<br />
                        <br />
                        if (currentState.Font != null)<br />
                            try { retVal.FontFamily = new FontFamily(currentState.Font); }<br />
                            catch {  } //Font name not found...<br />
<br />
                        if (currentState.FontSize.HasValue)<br />
                            retVal.FontSize = currentState.FontSize.Value;<br />
<br />
						break;<br />


If you figure out what caused the problem, please drop me a note.

I am hopping to implement some WPF binding as well (at least the most basic one, without converter).

Regards
Joseph Leung


GeneralRe: extensions Pin
Lee_Nover23-Mar-09 4:14
Lee_Nover23-Mar-09 4:14 
GeneralRe: extensions Pin
Leung Yat Chun23-Mar-09 10:20
Leung Yat Chun23-Mar-09 10:20 
GeneralRe: extensions Pin
Lee_Nover24-Mar-09 3:45
Lee_Nover24-Mar-09 3:45 
GeneralRe: extensions Pin
Leung Yat Chun25-Mar-09 9:20
Leung Yat Chun25-Mar-09 9:20 
GeneralRe: extensions Pin
Bob Ranck4-Apr-09 9:26
Bob Ranck4-Apr-09 9:26 
GeneralRe: extensions Pin
Leung Yat Chun5-Apr-09 20:45
Leung Yat Chun5-Apr-09 20:45 
QuestionFlow document? Pin
Member 17809897-Feb-09 21:32
Member 17809897-Feb-09 21:32 
AnswerRe: Flow document? Pin
Leung Yat Chun7-Feb-09 22:39
Leung Yat Chun7-Feb-09 22:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.