Silverlight to ASP.NET
To show Silverlight communicating with the ASP.NET site it is hosted within I have just set up a new Silverlight application and inserted a text box and a button, when I click the button I am wanting the Silverlight to change the property of the htmlText on the host page, to show the text entered in Silverlight.
First I must make sure that on the host (BlogDemo01TestPage.aspx) there is a item with the correct ID, here I have just used a header with ellipses.
1: <h3 id="htmlText">...</h3>
This is then used from the Silverlight code behind file to reference the object, so we can change the text. As we are wanting to talk via the browser to the ASP.NET page we must first add a new reference to the browser. Then with the Click event of the SL button.
1: using System.Windows.Browser;
3: namespace BlogDemo01
6: public partial class Page : UserControl
8: public Page()
13: private void Button_Click(object sender, RoutedEventArgs e)
This gets the element within the ASP.NET page with the ID of htmlText and replaces the innerText with that of what we entered in the SL text box.
ASP.NET to Silverlight
Now that we can successfully use Silverlight to communicate with the ASP.NET page we really would like it to happen in the opposite direction as well.
1: <html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;">
2: <head runat="server">
5: <body style="height:100%;margin:0;">
2: function htmlButtonClick()
4: var app = document.getElementById("Xaml1").Content.BlogDemo01;
7: <form id="form1" runat="server" style="height:100%;">
8: <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
10: <asp:Silverlight ID="Xaml1" Source="~/ClientBin/BlogDemo01.xap"
11: runat="server" MinimumVersion="2.0.31005.0" Width="200" Height="200"/>
13: <h3 id="htmlText">...</h3>
15: <button onclick="htmlButtonClick();" />
As you can see the code is now set up to call a method within the Silverlight page, which signature accepts no arguments and returns void.
1: namespace BlogDemo01
4: public partial class Page : UserControl
6: public Page()
10: HtmlPage.RegisterScriptableObject("BlogDemo01", this);
16: public void htmlClick()
18: this.textBox.Text = "Hello, World! from html.";