Calling a Javascript function from Silverlight

This article talks about how you can call a javascript function from Silverlight.

1. Create a Silverlight project of type ‘Silverlight Application’ in Visual Studio. You will get a dialog box asking you whether you want to host your application on a website. Check this checkbox and click on OK.

2. Open MainPage.xaml and replace the existing content with this:

<UserControl x:Class="Blog1.MainPage"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
 <Grid x:Name="LayoutRoot">

 <Button x:Name="testButton" Content="Call js function" Click="testButton_Click"
 Width="150" Height="40" />

 </Grid>
</UserControl>

3. In MainPage.xaml.cs, a method testButton_Click should have been created. Replace the method with the one below. If the method is not present already, add it yourself.

 private void testButton_Click(object sender, RoutedEventArgs e)
 {
 HtmlPage.Window.CreateInstance("calledFromSilverlight", new string[] { "Silverlight User" });
 }

4. Save all the files and build your solution.

5. Go to the Bin folder where the xap file is located. Normally under <project>/Bin/Debug. There should be a file named TestPage.html. Open this file in your Visual Studio and add the following function.

 function calledFromSilverlight(user) {
 alert("Hello " + user);
 }

6. Open this page in a browser. You should see a button with text ‘Call js function’. Click on this and if everything is fine, you should see a pop-up window saying ‘Hello Silverlight User’.

That’s it. You just invoked a javascript function from Silverlight. Wasn’t that easy?

Note:

  1. If you rebuild the solution, the TestPage.html is created again, removing all the changes that you have made. You can make a copy of this file, name it MyTestPage.html and add the javascript function in this.
  2. This works for Silverlight 3 and Visual Studio 2008.

Next up: Calling Silverlight method from Javascript.

Advertisements

One thought on “Calling a Javascript function from Silverlight

  1. […] Calling a Javascript function from Silverlight | Codelicious – Jan 07, 2010 · This article talks about how you can call a javascript function from Silverlight. 1. Create a Silverlight project of type ‘Silverlight Application’ in …… […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: