8 March 2010
In the future, once Silverlight 4 is out, I’ll of course make sure to update this to work with the rich text control to allow for copying and pasting as well, but in the meantime, this works great for displaying code.
A while ago I was happy to see that Drew Miller released a simple syntax highlighting engine called ColorCode. It is a good implementation that moves forward through a stream, provides scoping information, and is compact enough for client use.
The control, however, was designed to only target ASP.NET. It writes out the results using an HtmlWriter. I had to rip out a lot of this implementation requirement that was threaded throughout the code, but what I have now effectively takes a TextBlock and outputs a bunch of Inline elements to it for all the processed code.
Note that I did what it took to get this control functional, this isn’t any sort of reference implementation.
Here’s the source and quick sample in a Visual Studio 2010 Silverlight 3 project:
Add the control assembly to your Silverlight project. Then, add an XMLNS prefix to your Silverlight page where you’d like to use the control.
There are two properties of interest that should be set or bound: SourceCode (the actual source text), and SourceLanguage. The names probably could be better, sorry!
SourceCode dependency property is the source to syntax highlight, just like the Text property of a TextBlock. The name is different to make it clear that this is not just a TextBlock control since you also need to specify the language type to colorize.
This control is small enough that I think it’ll be useful inside code sample apps. It’s 40 KB uncompressed, and 16 KB in a typical Silverlight Xap.
The original ASP.NET implementation on CodePlex contained support for a lot of other additional languages and file types:
To add any of these to your control, you just need to:
Hope this helps.
Jeff Wilcox is a Principal Software Engineer at Microsoft in the Open Source Programs Office, helping Microsoft scale to 15,000+ engineers using, contributing to and releasing open source.