Accessing Silverlight Functions from Aspx Page Hosted Inside C1HtmlHost
C1HtmlHost is a wonderful control which gives you the ability to host web pages inside a Silverlight application. There are times when you would want to access a function defined in a Silverlight user control from an aspx page and it is possible with a few tricks. This blog is all about accessing a Silverlight function from an aspx page hosted inside C1HtmlHost control using Javascript.
Hosting an Aspx page inside C1HtmlHost
First of all, we need to add a WebForm to the web project, so add a new WebForm and name it WebForm1.aspx. You can put whatever content you want in the WebForm. A Button will be used later to access the function. Now we'll add a C1HtmlHost control to the Silverlight UserControl and set its source as WebForm1.aspx.
c1HtmlHost1.SourceUri = new Uri("WebForm1.aspx", UriKind.Relative);
Defining the Silverlight Function
Now suppose you wish to access the following Silverlight function:
public void SilverlightFunction()
{
MessageBox.Show("Message from Silverlight Function");
}
To make is accessible outside Silverlight, it needs to be declared as a ScriptableMember which is a part of the System.Windows.Browser namespace.
[ScriptableMember]
public void SilverlightFunction()
{
MessageBox.Show("Message from Silverlight Function");
}
The second step is to Register the Silverlight UserControl as a scriptable object with a name so that it can be accessed in Javascript. Open App.xaml.cs and write the following code:
private void Application_Startup(object sender, StartupEventArgs e)
{
MainPage newMainPage = new MainPage();
this.RootVisual = newMainPage;
HtmlPage.RegisterScriptableObject("slObject", newMainPage);
}
There's one other small thing that needs to be done: open the aspx page which hosts the Silverlight application (C1HtmlHost_SampleTestPage.aspx) and give an id to the Silverlight Object.
<object id="silverlightControl" data="data:application/x-silverlight-2,"
Accessing the Function in WebForm1.aspx
Now we come to the final part of how to access the function: add an input button and define its onclick event.
<input type="button" id="btn1" onclick="CallSilverlightFunction()" value="Call Silverlight Function" />
Write the following Javascript code in the CallSilverlightFunction() function:
function CallSilverlightFunction(sender, args) {
var parent = window.parent;
var sl = parent.document.getElementById("silverlightControl");
sl.Content.slObject.SilverlightFunction();
}
We need to find the parent window since WebForm1 is hosted inside C1HtmlHost. Then we need to find the Silverlight Object with id="SilverlightControl." Now we can easily access the function using the registered name (slObject) and the function name (SilverlightFunction). Please refer to the attached sample for complete implementation. Download Sample