Wednesday, July 9, 2008

Handle Silverlight event in javascript

This post will show you how to throw events from Silverlight controls in managed code and catch them in javascript. Such a scenario comes while building HTML bridge in Beta 2, when you need to catch the events from Silverlight UserControls in the aspx page hosting them. We'll take the example of ListBox SelectionChanged Event. Whenever Listbox's selection is changed in the SL user control we'll show an alert on javascript which is having that SelectedText from the Listbox. Firstly the UserControl say UserControl1 which will throw the event, needs to have an event and a property marked with ScriptableMemberAttribute which is found under System.Windows.Browser. So here is how you add Scriptable members

private string _selectedText;
[ScriptableMemberAttribute]
public string SelectedText{
get{
return _selectedText;
}
}
[ScriptableMemberAttribute]
public event EventHandler MySelectionChanged;



Then we'll add the code the update the SelectedText property whenever ListBox selection is changed



private void lstMaster_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
_selectedText= lstMaster.SelectedItem.ToString();
if (MySelectionChanged != null)
{
MySelectionChanged(sender,e);
}
}



The above code also raises the event which will be caught in JS

After this you need to register UserControl1 in the App.xaml file so that it available to the host aspx page's javascript. This is code you need to write for that

private void Application_Startup(object sender, StartupEventArgs e)
{
UserControl1 objPage = new UserControl1();
HtmlPage.RegisterScriptableObject("registerPage", objPage);
}


Then finally we'll register an event handler for our custom event to a javascript method. This is done by on the OnPluginLoaded attribute of the <asp:Silverlight> control tag. Here's the code for that


//Adding javascript event listener
function hookEvent(sender){
var UC=sender.get_element();
UC.Content.registerPage.addEventListener("MySelectionChanged",jsEventHandler);
}

function jsEventHandler(sender,args){
var UC=document.getElementById("Xaml1");
alert( UC.Content.registerPage.SelectedText);
}



No comments: