Clickable Hyperlinks in a Silverlight TextBlock
[updated 7/12/09 to Silverlight 3 RTW]
I’m contemplating porting an application I wrote in Flex over to Silverlight. One requirement would be to display a bunch of formatted text with some of the contents formatted like HTML hyperlinks. The links must be clickable so I can display a callout explaining that particular piece of text. I searched the web for clickable links in Silverlight but came up empty handed. There are a few examples of displaying rich, formatted text (see Demo app below for links) but making parts clickable seems to be fleeting.
Silverlight’s TextBlock (tutorial here) control enables you to format the text (unlike TextBox), but locating the exact text that is being clicked proves to be a problem if the text is one monolithic mass. In my original Flex app, I used a combination of TextMetrics and the current mouse position to figure things out, but that level of text functionality is currently not available in Silverlight.
What I’ve done, and may prove to be a better solution, is to piggyback Delay’s great HTMLTextBlock but I break out the hyperlinks ( <a> ,,, </a> ) into their own TextBlock so I can deal with MouseEnter (to change the cusor to a Hand) and LeftMouseButtonUp (to Navigate to another URL). I end up with a Model consisting of a number of TextBlock controls that I display via an ItemsControl whos ItemsPanelTemplate is a WrapPanel (from the Silverlight Toolkit) . If the WrapPanel is released with Silverlight 3, I’ll update this post.
The best way to view the Demo is to open it in your browser so you can use the Back button after testing a link. (guess I could make this a Navigation App) as well as see how the combination of TextBlock’s Wrapping and WrapPanel do a decent job of re-rendering on browser resizing.
Here’s the Demo in this page so you can see what’s up but will not be able to see the resize behavior. The Visual Studio solution is here (Sliverlight 3 Beta). – Cheers!
Your browser does not support iframes.