One of the challenges I ran across recently in Silverlight 3 was the need to display HTML content within a datagrid cell.
I did a Google search similar to ”silverlight html content” and quickly discovered that there aren’t any good solutions out there right now. Basically, the solutions I found were the following:
- Creative hacks using the IFRAME tag and clever positioning (this includes the C1HtmlHost control by ComponentOne, which basically uses this technique).
- Use the HtmlTextBlock control that’s been blogged about (supports only very basic HTML tags; no CSS).
- Create your own custom control.
None of these solutions worked well for me because the HTML I needed to display was slightly too complicated for the HtmlTextBlock control to handle, and I had problems getting the C1HtmlHost control by ComponentOne to work within a datagrid cell (the browser would lock up, for example, whenever the datagrid was scrolled or data was refreshed).
But, thankfully, ComponentOne has another control called C1RichTextBox that renders HTML nicely without using any IFRAME hacks. I wouldn’t necessarily recommend it if you need to host an external HTML page within your application (because, for example, it doesn’t supported externally linked stylesheets), but it works well for basic scenarios that require more HTML support than what HtmlTextBlock provides. It also works well within a datagrid cell, which was essential for my scenario.
My final XAML code for hosting HTML within a datagrid cell looks like this:
<c1dg:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<c1rtb:C1RichTextBox Background="Transparent"
BorderThickness="0"
IsReadOnly="True"
VerticalScrollBarVisibility="Hidden"
Html="{Binding HtmlBackingField}" />
<Rectangle Fill="Transparent" />
</Grid>
</DataTemplate>
</c1dg:DataGridTemplateColumn.CellTemplate>
The reason for the ‘Rectangle’ tag is that I needed to create a transparent panel (“glass pane”) in front of the C1RichTextBox control. This is both an easy way to shield the textbox from user interaction (making it truly read-only) and also allows the datagrid to behave normally when the cell is clicked. Without the transparent panel, the textbox intercepts the click event and prevents the datagrid from highlighting the row as it should.
And remember, this approach is geared towards creating an ”HTML viewer,” not a “web browser.” If you need a true “web browser” control (i.e. something that acts like an IFRAME and can fully host and support external web pages where many files, such as CSS files, have to be linked together to render the HTML), you’ll need to keep searching for another solution. This approach is what I’d call a middle-of-the-road solution, but in many cases, it’ll get the job done.