Monday, June 6, 2011

Html To Silverlight

Hi again,

here i am coming again with a nice and fresh snippet :)

So, the other day i had a question at work, how can we interact with Silverlight from our Asp.Net application? Immediatly i thought about javascript, because it's known that silverlight and javascript have a great interoperability.

The solution i found, allow to expose a silverlight class methods to javascript, wich means something like this:

Note that i added a attribute to my method that says my method will be a member of my silverlight object when i will access it through javascript.

In javascript i will simply need to use it:

function SendToSilverlight() {
silverlightClient.Content.SilverlightPage.UpdateTextFromBrowser("Teste 1","Teste 2");

This is my javascript method that will update my silverlight textbox. Very important, you must initialize the variable 'silverlightClient' in the load event of the silverlight control, so in order to do that add the param to your html silverlight object:

and create the function pluginLoaded in the javascript:

var silverlightClient;
function pluginLoaded(sender, args) {
silverlightClient = sender.getHost();

Great hmm? ok, but it is not working yet, why?!

We need to register our sivlerlight object as a ScriptableObject in our html page. You can do that in the Silverlight Application_Startup event handler like this:

private void Application_Startup(object sender, StartupEventArgs e)
var page = new MainPage();

this.RootVisual = page;

HtmlPage.RegisterScriptableObject("SilverlightPage", page);

And this is evertyhing you need ;)

Source Code:

No comments:

Post a Comment