15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

1112 ❘ ChaPTer 38 silverliGht<br />

javascript Calling silverlight<br />

To make a .<strong>NET</strong> method available from JavaScript, the attribute ScriptableMember must be applied.<br />

If you would like to make all members of a class available from JavaScript, you can apply the attribute<br />

ScriptableType instead. Here, the attribute ScriptableMember is applied to the method ToUpper(),<br />

which changes the input string to uppercase.<br />

[ScriptableMember]<br />

public string ToUpper(string s)<br />

{<br />

return s.ToUpper();<br />

}<br />

code snippet JavaScriptInterop/MainPage.xaml.cs<br />

The type containing scriptable members must be registered with the HTML page so that it can be found by<br />

scripting. This is done by invoking the RegisterScriptableObject() method from the HtmlPage class.<br />

The first argument of this method is a key name that is used by JavaScript to find the object. The second<br />

argument defines the instance that is used to access the scriptable members.<br />

public MainPage()<br />

{<br />

InitializeComponent();<br />

//...<br />

}<br />

HtmlPage.RegisterScriptableObject("ScriptKey", this);<br />

Now it is possible to access the .<strong>NET</strong> code from JavaScript. To find the scriptable object from JavaScript,<br />

the Silverlight control must be accessed. To make this easier, an id attribute is added to the object tag that<br />

references the Silverlight package. Also, text <strong>and</strong> button elements are added to the HTML code. The button<br />

has the JavaScript function callDotnet() assigned to the onclick event where the call to managed<br />

code happens.<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

code snippet SilverlightDemos.Web/JavaScripInteropTestPage.html<br />

The JavaScript function callDotnet() uses the plugin identifier to find the Silverlight control with<br />

getElementById(). By using the ScriptKey defined earlier with the registration, the scriptable type can<br />

now be accessed. Using this scriptable type, the method ToUpper() is now available to change the input<br />

to uppercase.<br />

function callDotnet() {<br />

var plugin = document.getElementById("plugin");<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!