
Binding the HTML Button Event to XAML Code
An App.xaml file is automatically created when you create a Silverlight project. The code-behind file for the App.xaml file (App.xaml.cs for C# and App.xaml.vb for Visual Basic) defines an App class that contains an Application_Startup method. You can write code in this method to bind or establish a connection between your Web page and a managed class.
To bind a client event to XAML code
Open the code-behind class file for the App.xaml file.
At the top of the file, add a using or Imports statement to import the System.Windows.Browser namespace.
Add code to the Application_Startup method that performs the following tasks:
Gets a reference to the System.Windows.Browser..::.HtmlDocument object.
Creates a delegate for a method named CallGlobalJSMethod in the current class.
Binds the CallGlobalJSMethod method to the click event of the HTML button using the document reference and the delegate.
The following example shows the completed Application_Startup method.
private void Application_Startup(object sender, StartupEventArgs e) {
this.RootVisual = new Page();
// HtmlDocument requires using System.Windows.Browser;
HtmlDocument doc = HtmlPage.Document;
// Hook up the simple JScript method HTML button.
doc.GetElementById("btnCallJSMethod").AttachEvent("click",
new EventHandler(this.CallGlobalJSMethod));
}
Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
Me.RootVisual = New Page()
' HtmlDocument requires Imports System.Windows.Browser
Dim doc As HtmlDocument = HtmlPage.Document
Dim del As New EventHandler(AddressOf Me.CallGlobalJSMethod)
' Hookup the simple JScript method HTML button.
doc.GetElementById("btnCallJSMethod").AttachEvent("click", del)
End Sub
In the App class, add the CallGlobalJSMethod method to perform the following tasks:
Get the current date and time and build it into a string that indicates that the date and time was calculated in managed code.
Call the HtmlPage.Window.Invoke method to call the client-script function named globalJSMethod, passing it the date-time string.
The following example shows the completed CallGlobalJSMethod method.
// Call a global JScript method defined on the HTML page.
private void CallGlobalJSMethod(object o, EventArgs e) {
string strMS = DateTime.Now.Millisecond.ToString();
string strTime = "Time came from managed code \n"
+ DateTime.Now.ToLongTimeString()
+ " MS = " + strMS;
HtmlPage.Window.Invoke("globalJSMethod", strTime);
}
' Call a global JScript method defined on the HTML page.
Private Sub CallGlobalJSMethod(ByVal sender As Object, ByVal e As EventArgs)
Dim strMS As String = DateTime.Now.Millisecond.ToString()
Dim strTime As String = "Time came from managed code" + ControlChars.NewLine _
+ DateTime.Now.ToLongTimeString() _
+ " MS = " + strMS
HtmlPage.Window.Invoke("globalJSMethod", strTime)
End Sub