Calling C# events from javascript in Silverlight:
I have explained here the way to call C# events from silverlight. This is one of the most basic example and it works well. Suppose we have a function in the codebehind, which is CallMe().We must call it from javascript or, say from the HTML page where the silverlight control is called.
For this to happen we should declare the function as [ScriptableMember] in C# . This C# attribute is declared to tell the compiler at runtime to indicate that a specific property, method, or event is accessible to JavaScript callers.
Say we have the following function.
[ScriptableMember]
public void CallMe()
{
HtmlPage.Window.Alert("Eurekaaaaaaa......");
}
Note:If this doesnt work, we must also declare the class containing this method as [ScriptableType].
Now we must register in the App.Xaml.cs,
private void Application_Startup(object sender, StartupEventArgs e)
{
Page page=new Page();//This is if the child silverlight element is Page.xaml.
this.RootVisual = page;
HtmlPage.RegisterScriptableObject("scriptableMethod", page);
}
What we do in the above code is registering the scriptable method on the object page. The "scriptableMethod" acts as key to the Scriptable members on Page.
We call a javascript to create the silverlight application.
Now in the Html page where we call the object of the silverlight application,
we make a button that on click would call this function.
function createSilverlight( controlHost )
{
Silverlight.createObjectEx({
source: "ClientBin/XMLtest.xap",
parentElement: controlHost,
id: "XMLtestScriptable",
properties: {
width: "500",
height: "500",
version: "2.0.31005.0",
background: "white",
isWindowless: "true",
enableHtmlAccess: "true"
},
events: {}
});
}
We call this javascript to create the silverlight control on the screen.
script type="text/javascript">
// Find the div by id
var hostElement = document.getElementById("silverlightControlHost");
// Create the Silverlight control
createSilverlight(hostElement);
Now we include in the page a button, on click of the button, the function will be called.
<input onclick="document.getElementById('XMLtestScriptable').Content.Method.CallMe() " value="Alert" type="button" name="Alert">
.On click of this button it will execute the CallMe() method in silverlight codebehind
No comments:
Post a Comment