Friday, September 14, 2007

Embedding Silverlight using a .NET control

How to use Flash in websites is common knowledge by now. Silverlight, however, is a different story.
Showing a Silverlight object in a page (especially multiple objects) requires a different approach.The developer needs to create multiple javascript functions and call these on exact location in HTML where they want to show the object. When using multiple objects on one page, it is possible to use only one javascript file, but this makes it less maintainable then using one script for each object.


For using a single Silverlight object in a page, the following lines of code are required:

We have created a SilverlightPanel in .NET that does this for you. Our panel inherits the System.Web.UI.WebControls.Panel, overrides the OnLoad and Render methods and uses the following properties:

  • ScriptPath
  • CreateFunctionName

Usage example:

This one line does the same as the lines above, but has the following advantages:
Using the default embedding method in combination with the ASP.NET AJAX framework (
http://ajax.asp.net) doesn't work.
You have to add the registration of the javascript file to the scriptmanager that is necessary for using ASP.NET AJAX.
The control we created checks if there is a scriptmanager on the page. If so, it automatically registers the script with the scriptmanager. If not, the javascript is registered in the page like you normally would do.

It is possible to use this control from a web user control without having to change the aspx file in which it is used. By using the RegisterClientScriptInclude it automatically puts the javascript on the first few lines of the HTML that is sent to the browser. You don't have to worry about correct placement of the javascript.

With this method, it is possible to use one javascript file per XAML file. This makes it more readable and easier to maintain.
When Microsoft decides to change the way Silverlight objects are embedded, only this control needs to be changed instead of multiple pages, sites, ascx controls, etc.


You can download the project here

2 comments:

  1. What do you think about Tom Sneath's approach, which avoids this altogether by using iframes referencing the Silverlight server: http://blogs.msdn.com/tims/archive/2007/07/31/iframe-support-in-silverlight-streaming.aspx

    Thanks,
    Charlie
    www.NoonmarkAntiques.com

    ReplyDelete