Friday, 1 June 2007

HOWTO: Make your Silverlight 1.1 Application Scriptable

Here's how to make your Silverlight application scriptable from JavaScript. I'll use my SilverNibbles application as an example, and we will make it so that you can start a new game by pressing an ordinary HTML button that calls into the Silverlight application.

This requires us to make our Page class scriptable. We will also make the NewGame function accessible to JavaScript. First we must mark both the Page class and the NewGame function with the Scriptable attribute, found in the System.Windows.Browser namespace.

using System.Windows.Browser;
...
namespace SilverNibbles
{
[Scriptable]
public partial class Page : Canvas
{
...

[Scriptable]
public void NewGame(int players)
{
...

The next step is to register a variable that JavaScript can use to access the instance of the Page class. We do this in the Page's Loaded event handler. We have chosen to call our instance, "SilverNibbles".

public void Page_Loaded(object o, EventArgs e)
{
...
WebApplication.Current.RegisterScriptableObject("SilverNibbles", this);

Now we will create some buttons in our main HTML page that will start a new game, along with some JavaScript that handles them. Notice I have set the focus to the Silverlight control which will ensure we have keyboard focus for the new game. Also notice that our registered scriptable object is referenced as a member of the Content property of the Silverlight control.

<script src="Silverlight.js" type="text/javascript"></script>
<script src="SilverNibbles.html.js" type="text/javascript"></script>
<script type="text/javascript">
function onNewGameClick(players) {
var silverlight = document.getElementById('SilverlightControl');
silverlight.focus();
silverlight.Content.SilverNibbles.NewGame(players);
}
</script>
...

<p>New game:
<input onclick="onNewGameClick(1)" type="button" value="One Player">
<input onclick="onNewGameClick(2)" type="button" value="Two Players">
</p>
Post a Comment