Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

WPF HTML Supported TextBlock

, 7 Feb 2009
This article describes HtmlTextBlock which is a WPF TextBlock that can parse a limited set of HTML tags and display them.
/*
 * Created by SharpDevelop.
 * User: LYCJ
 * Date: 20/10/2007
 * Time: 23:25
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Controls;
using System.Windows.Documents;

namespace QuickZip.MiniHtml2
{
	
	
	/// <summary>
	/// Description of Updater.
	/// </summary>
	public class HtmlUpdater
	{
		TextBlock textBlock;
		CurrentStateType currentState = new CurrentStateType();		
		
		private void UpdateStyle(HtmlTag aTag)
		{
			currentState.UpdateStyle(aTag);
		}
		
		private Inline UpdateElement(HtmlTag aTag)
		{
			Inline retVal = null;
			
			switch (aTag.Name)
			{
				case "text" : 
						retVal = new Run(aTag["value"]);
						
						if (currentState.Bold) retVal = new Bold(retVal);
						if (currentState.Italic) retVal = new Italic(retVal);
						if (currentState.Underline) retVal = new Underline(retVal);
						break;
				case "br" : 
						retVal = new LineBreak();
						break;
			}


            if (currentState.HyperLink != null && currentState.HyperLink != "")
            {
                Hyperlink link = new Hyperlink(retVal);
                try
                {
                    link.NavigateUri = new Uri(currentState.HyperLink);
                }
                catch
                {
                    link.NavigateUri = null;
                }
                retVal = link;
            }
			
			return retVal;
		}		
		
		public HtmlUpdater(TextBlock aBlock)
		{
			textBlock = aBlock;
		}
		
		public void Update(HtmlTagTree tagTree)
		{			
			List<HtmlTag> tagList = tagTree.ToHtmlTagList();
			
			foreach (HtmlTag tag in tagList)
			{
				switch (Defines.BuiltinTags[tag.ID].flags)
				{
					case HTMLFlag.TextFormat : UpdateStyle(tag); break;
					case HTMLFlag.Element : textBlock.Inlines.Add(UpdateElement(tag)); break;
				}
					
			}						
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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

Share

About the Author


| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 7 Feb 2009
Article Copyright 2009 by Leung Yat Chun
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid