Looking for a way to display HTML content within a Silverlight application? If you haven’t tried doing that before it can be challenging at first until you know a few tricks of the trade. Being able to display HTML is especially handy when you’re required to display RSS feeds (with embedded HTML), SQL Server Reporting Services reports, PDF files (not actually HTML – but the techniques discussed will work), or other HTML content. In this post I'll discuss three options for displaying HTML content in Silverlight applications and describe how my company is using these techniques in client applications. Displaying HTML Overlays If you need to display HTML over a Silverlight application (such as an RSS feed containing HTML data in it) you’ll need to set the Silverlight control’s windowless parameter to true. This can be done using the object tag as shown next: <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="ClientBin/HTMLAndSilverlight.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="4.0.50401.0" />
<param name="autoUpgrade" value="true" />
<param name="windowless" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0" style="text-decoration:none">
<img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
</a>
</object>
By setting the control to “windowless” you can overlay HTML objects by using absolute positioning and other CSS techniques. Keep in mind that on Windows machines the windowless setting can result in a performance hit when complex animations or HD video are running since the plug-in content is displayed directly by the browser window. It goes without saying that you should only set windowless to true when you really need the functionality it offers. For example, if I want to display my blog’s RSS content on top of a Silverlight application I could set windowless to true and create a user control that grabbed the content and output it using a DataList control:
<style type="text/css">
a {text-decoration:none;font-weight:bold;font-size:14pt;}
</style>
<div style="margin-top:10px; margin-left:10px;margin-right:5px;">
<asp:DataList ID="RSSDataList" runat="server" DataSourceID="RSSDataSource">
<ItemTemplate>
<a href='<%# XPath("link") %>'><%# XPath("title") %></a>
<br />
<%# XPath("description") %>
<br />
</ItemTemplate>
</asp:DataList>
<asp:XmlDataSource ID="RSSDataSource" DataFile="http://weblogs.asp.net/dwahlin/rss.aspx"
XPath="rss/channel/item" CacheDuration="60" runat="server" />
</div>
The user control can then be placed in the page hosting the Silverlight control as shown below. This example adds a Close button, additional content to display in the overlay window and the HTML generated from the user control.
<div id="RSSDiv">
<div style="background-color:#484848;border:1px solid black;height:35px;width:100%;">
<img alt="Close Button" align="right" src="Images/Close.png" onclick="HideOverlay();" style="cursor:pointer;" />
</div>
<div style="overflow:auto;width:800px;height:565px;">
<div style="float:left;width:100px;height:103px;margin-left:10px;margin-top:5px;">
<img src="http://weblogs.asp.net/blogs/dwahlin/dan2008.jpg" style="border:1px solid Gray" />
</div>
<div style="float:left;width:300px;height:103px;margin-top:5px;">
<a href="http://weblogs.asp.net/dwahlin" style="margin-left:10px;font-size:20pt;">Dan Wahlin's Blog</a>
</div>
<br /><br /><br />
<div style="clear:both;margin-top:20px;">
<uc:BlogRoller ID="BlogRoller" runat="server" />
</div>
</div>
</div>
Of course, we wouldn’t want the RSS HTML content to be shown until requested. Once it’s requested the absolute position of where it should show above the Silverlight control can be set using standard CSS styles. The following ID selector named #RSSDiv handles hiding the overlay div shown above and determines where it will be display on the screen.
#RSSDiv
{
background-color:White;
position:absolute;
top:100px;
left:300px;
width:800px;
height:600px;
border:1px solid black;
display:none;
}
Now that the HTML content to display above the Silverlight control is set, how can we show it as a user clicks a HyperlinkButton or other control in the application? Fortunately, Silverlight provides an excellent HTML bridge that allows direct access to content hosted within a page. The following code shows two JavaScript functions that can be called from Siverlight to handle showing or hiding HTML overlay content. The two functions rely on jQuery (http://www.jQuery.com) to make it easy to select HTML objects and manipulate their properties:
function ShowOverlay()
{
rssDiv.css('display', 'block');
}
function HideOverlay()
{
rssDiv.css('display', 'none');
}
Calling the ShowOverlay function is as simple as adding the following code into the Silverlight application within a button’s Click event handler:
private void OverlayHyperlinkButton_Click(object sender, RoutedEventArgs e)
{
HtmlPage.Window.Invoke("ShowOverlay");
}
The result of setting the Silverlight control’s windowless parameter to true and showing the HTML overlay content is shown in the following screenshot:
Thinking Outside the Box to Show HTML Content
Setting the windowless parameter to true may not be a viable option for some Silverlight applications or you may simply want to go about showing HTML content a different way. The next technique I’ll show takes advantage of simple HTML, CSS and JavaScript code to handle showing HTML content while a Silverlight application is running in the browser. Keep in mind that with Silverlight’s HTML bridge feature you can always pop-up HTML content in a new browser window using code similar to the following:
System.Windows.Browser.HtmlPage.Window.Navigate(
new Uri("http://silverlight.net"), "_blank");
For this example I’ll demonstrate how to hide the Silverlight application while maximizing a container div containing the HTML content to show. This allows HTML content to take up the full screen area of the browser without having to set windowless to true and when done right can make the user feel like they never left the Silverlight application. The following HTML shows several div elements that are used to display HTML within the same browser window as the Silverlight application:
<div id="JobPlanDiv">
<div style="vertical-align:middle">
<img alt="Close Button" align="right" src="Images/Close.png" onclick="HideJobPlanIFrame();" style="cursor:pointer;" />
</div>
<div id="JobPlan_IFrame_Container" style="height:95%;width:100%;margin-top:37px;"></div>
</div>
The JobPlanDiv element acts as a container for two other divs that handle showing a close button and hosting an iframe that will be added dynamically at runtime. JobPlanDiv isn’t visible when the Silverlight application loads due to the following ID selector added into the page:
#JobPlanDiv
{
position:absolute;
background-color:#484848;
overflow:hidden;
left:0;
top:0;
height:100%;
width:100%;
display:none;
}
When the HTML content needs to be shown or hidden the JavaScript functions shown next can be used:
var jobPlanIFrameID = 'JobPlan_IFrame';
var slHost = null;
var jobPlanContainer = null;
var jobPlanIFrameContainer = null;
var rssDiv = null;
$(document).ready(function ()
{
slHost = $('#silverlightControlHost');
jobPlanContainer = $('#JobPlanDiv');
jobPlanIFrameContainer = $('#JobPlan_IFrame_Container');
rssDiv = $('#RSSDiv');
});
function ShowJobPlanIFrame(url)
{
jobPlanContainer.css('display', 'block');
$('<iframe id="' + jobPlanIFrameID + '" src="' + url + '" style="height:100%;width:100%;" />')
.appendTo(jobPlanIFrameContainer);
slHost.css('width', '0%');
}
function HideJobPlanIFrame()
{
jobPlanContainer.css('display', 'none');
$('#' + jobPlanIFrameID).remove();
slHost.css('width', '100%');
}
ShowJobPlanIFrame() handles showing the JobPlanDiv div and adding an iframe into it dynamically. Once JobPlanDiv is shown, the Silverlight control host has its width set to a value of 0% to allow the control to stay alive while making it invisible to the user. I found that this technique works better across multiple browsers as opposed to manipulating the Silverlight control host div’s display or visibility properties.
Now that you’ve seen the code to handle showing and hiding the HTML content area, let’s switch focus to the Silverlight application. As a user clicks on a link such as “View Report” the ShowJobPlanIFrame() JavaScript function needs to be called. The following code handles that task:
private void ReportHyperlinkButton_Click(object sender, RoutedEventArgs e)
{
ShowBrowser(_BaseUrl + "/Report.aspx");
}
public void ShowBrowser(string url)
{
HtmlPage.Window.Invoke("ShowJobPlanIFrame", url);
}
Any URL can be passed into the ShowBrowser() method which handles invoking the JavaScript function. This includes standard web pages or even PDF files. We’ve used this technique frequently with our SmartPrint control (http://www.smartwebcontrols.com) which converts Silverlight screens into PDF documents and displays them. Here’s an example of the content generated:
Silverlight 4’s WebBrowser Control
Both techniques shown to this point work well when Silverlight is running in-browser but not so well when it’s running out-of-browser since there’s no host page that you can access using the HTML bridge. Fortunately, Silverlight 4 provides a WebBrowser control that can be used to perform the same functionality quite easily. We’re currently using it in client applications to display PDF documents, SSRS reports and standard HTML content. Using the WebBrowser control simplifies the application quite a bit since no JavaScript is required if the application only runs out-of-browser.
Here’s a simple example of defining the WebBrowser control in XAML. I typically define it in MainPage.xaml when a Silverlight Navigation template is used to create the project so that I can re-use the functionality across multiple screens.
<Grid x:Name="WebBrowserGrid" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Visibility="Collapsed">
<StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Border Background="#484848" HorizontalAlignment="Stretch" Height="40">
<Image x:Name="WebBrowserImage" Width="100" Height="33" Cursor="Hand" HorizontalAlignment="Right"
Source="/HTMLAndSilverlight;component/Assets/Images/Close.png"
MouseLeftButtonDown="WebBrowserImage_MouseLeftButtonDown" />
</Border>
<WebBrowser x:Name="JobPlanReportWebBrowser" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</StackPanel>
</Grid>
Looking through the XAML you can see that a close image is defined along with the WebBrowser control. Because the URL that the WebBrowser should navigate to isn’t known at design time no value is assigned to the control’s Source property. If the XAML shown above is left “as is” you’ll find that any HTML content assigned to the WebBrowser doesn’t display properly. This is due to no height or width being set on the control. To handle this issue the following code is added into the XAML’s code-behind file to dynamically determine the height and width of the page and assign it to the WebBrowser. This is done by handling the SizeChanged event.
void MainPage_SizeChanged(object sender, SizeChangedEventArgs e)
{
WebBrowserGrid.Height = JobPlanReportWebBrowser.Height = ActualHeight;
WebBrowserGrid.Width = JobPlanReportWebBrowser.Width = ActualWidth;
}
When the user wants to view HTML content they click a button which executes the code shown in next:
public void ShowBrowser(string url)
{
if (Application.Current.IsRunningOutOfBrowser)
{
JobPlanReportWebBrowser.NavigateToString("<html><body><iframe src='" + url + "' style='width:100%;height:97%;' /></body></html>");
WebBrowserGrid.Visibility = Visibility.Visible;
}
else
{
HtmlPage.Window.Invoke("ShowJobPlanIFrame", url);
}
}
private void WebBrowserImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
WebBrowserGrid.Visibility = Visibility.Collapsed;
}
Looking through the code you’ll see that it checks to see if the Silverlight application is running out-of-browser and then either displays the WebBrowser control or runs the JavaScript function discussed earlier. Although the WebBrowser control’s Source property could be assigned the URI of the page to navigate to, by assigning HTML content using the NavigateToString() method and adding an iframe, content can be shown from any site including cross-domain sites. This is especially handy when you need to grab a page from a reporting site that’s in a different domain than the Silverlight application.
Here’s an example of viewing PDF file inside of an out-of-browser application. The first image shows the application running out-of-browser before the user clicks a PDF HyperlinkButton. The second image shows the PDF being displayed.
While there are certainly other techniques that can be used, the ones shown here have worked well for us in different applications and provide the ability to display HTML content in-browser or out-of-browser. Feel free to add a comment if you have another tip or trick you like to use when working with HTML content in Silverlight applications.
Download Code Sample
For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit http://www.thewahlingroup.com.