Blog

All Blog Posts

Using Silverlight in a User Control

Including a Silverlight application in a user control was not as easy as I expected... In a recent project I created a new Silverlight application which was going to be included in an existing ASP.NET website. The Silverlight application was going to be called from a User Control (myfile.ascx) in the site.

So far, no problem. I started to implement my code to log exceptions from Silverlight to the web server via the HtmlPage.Window.Invoke method. This did not work as I expected. I first tried to add my Javascript methods and ASP.NET Web Methods inside my user control (myfile.ascx). This did not work. After some research and testing I found the solution to my problem. Here is a summary of the changes which resolved my problem:
  • Template.master (Master page for all pages on the site)
    • Updated the ScriptManager tag (add one if you don't have one already) by adding the property:  EnablePageMethods="true"
  • Default.aspx.  (Contains the user control)
    • Added my Javascript methods in here.  The Silverlight application contained in my user control (myfile.ascx) will communicate with this page.
    • Added in the code-behind the Web Methods called by the Javascript methods.
  • myfile.ascx (contains the Silverlight application)
    • No changes - just contains the necessary code to host my Silverlight application.
After completing these changes my Silverlight application is happy again. The best news is that when I added another Silverlight application to this solution everything was already to roll. I was able to use the Web Methods I had previously included in Default.aspx. I hope you find this tip useful!

Thanks and keep on coding!