A developer asked me recently how to format text in Windows Store apps. Specifically he wanted to add bullet points to some article text he was displaying.
The sample templates like GridApp include a special class called RichTextColumns under the Common folder. This class wraps a normal RichTextBlock (which would run off the screen if its text got too long) to splits it into multiple columns by generating more RichTextBlocks for any overflow. There’s a property on RichTextColumns where you specify the content to be displayed called RichTextContent. It’s where any child markup in Xaml gets stored at runtime. So, in order to format the text, we need to change the content of the RichTextContent property.
It turns out the RichTextContent property is a RichTextBlock, so anything you can do with a RichTextBlock can be spread across multiple columns. That makes sense. The trick is usually to convert from some standard markup you know (let’s say HTML) to the child elements supported by RichTextBlock. There are several ways to do this but my favorite is to make a new control called HtmlRichTextColumns that inherits from RichTextColumns and can parse HTML content. Here are the steps:
- Remove sealed from RichTextColumns so we can inherit from it.
- Change ResetOverflowLayout to protected instead of private so we can call it from our inherited class.
- Create a new class called HtmlRichTextColumns and inherit from RichTextColumns.
- Add a dependency property called Markup with a type of string. Use the version of PropertyMetadata that calls a method whenever the value changes and have it call a private method MarkupChanged.
- In MarkupChanged, parse the text into Runs, Images, etc. and add them to the RichTextContent property. Then call ResetOverflowLayout to generate the columns.
Parsing the HTML itself is outside the scope of this article (maybe I’ll cover it in a later post). For now I’ll point you to the forum thread How to Convert Html to a RichTextBlock content. To the specific question about bullet points, well unfortunately the List tag isn’t supported in Windows 8. Shane Melbourne found a decent workaround by using indented paragraphs and symbols. You can read how he did it in the forum thread RichTextBlock Bullet list.