Click here to Skip to main content
Licence LGPL3
First Posted 7 Feb 2009
Views 40,980
Downloads 435
Bookmarked 25 times

WPF HTML Supported TextBlock

By Leung Yat Chun | 7 Feb 2009
This article describes HtmlTextBlock which is a WPF TextBlock that can parse a limited set of HTML tags and display them.

1

2

3
1 vote, 33.3%
4
2 votes, 66.7%
5
4.75/5 - 3 votes
μ 4.75, σa 1.01 [?]
  • Download source - 240.92 KB
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.

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 < >.

<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.

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)

About the Author

Leung Yat Chun

Software Developer

Hong Kong Hong Kong

Member
DirectoryInfoEx - 0.22
 
WPF FileExplorer - 0.8
 
WPF ListView MultiSelect - 0.4
 
WPF Aero Titlebar - 0.2

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionUnable to download the attached sample Pinmemberksvimalraj18:28 28 Jul '11  
AnswerRe: Unable to download the attached sample PinmemberLeung Yat Chun4:52 29 Jul '11  
GeneralSmall bug PinmemberArlenFeldman15:55 25 Mar '11  
GeneralThis is ... PinmemberXmen W.K.6:25 2 Jul '10  
GeneralSaving me a lot of time! PinmemberMember 32408306:01 12 Dec '09  
Generalimage in text block Pinmemberpathurun22:35 8 Sep '09  
GeneralRe: image in text block PinmemberLeung Yat Chun1:56 15 Sep '09  
GeneralDoes not work if Html Text is assigned to the HtmlTextBlock during Binding Pinmemberazamsharp11:09 1 Jul '09  
GeneralRe: Does not work if Html Text is assigned to the HtmlTextBlock during Binding PinmemberLeung Yat Chun8:06 2 Jul '09  
Generalextensions PinmemberLee_Nover16:11 20 Mar '09  
GeneralRe: extensions PinmemberLeung Yat Chun21:35 20 Mar '09  
GeneralRe: extensions PinmemberLee_Nover5:14 23 Mar '09  
GeneralRe: extensions PinmemberLeung Yat Chun11:20 23 Mar '09  
GeneralRe: extensions PinmemberLee_Nover4:45 24 Mar '09  
GeneralRe: extensions PinmemberLeung Yat Chun10:20 25 Mar '09  
GeneralRe: extensions PinmemberBob Ranck10:26 4 Apr '09  
GeneralRe: extensions PinmemberLeung Yat Chun21:45 5 Apr '09  
QuestionFlow document? PinmemberMember 178098922:32 7 Feb '09  
AnswerRe: Flow document? PinmemberLeung Yat Chun23:39 7 Feb '09  
GeneralRe: Flow document? PinmemberMember 178098923:38 8 Feb '09  
GeneralRe: Flow document? PinmemberLeung Yat Chun10:04 9 Feb '09  

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

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120209.1 | Last Updated 7 Feb 2009
Article Copyright 2009 by Leung Yat Chun
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid