In this tip we will discuss how to call a Silverlight function from our Javascript code and also the reverse technique. All the javascript functions discussed here should belong on the same aspx page where the Silverlight control is present.
Calling a Silverlight function from Javascript
I have a class, say, ‘Common’ in my Silverlight app inside which there is a function called CreateCircle and this function accepts parameters like pkId, colorValue, X_Y_Coordinate. This function creates a circle with these input parameters.Now my requirement is to call this function from the aspx page (of course this would be the same aspx page which will host the silverlight control).
Following are the steps to be followed for this
Step1:The function that needs to be called must be prefixed with the [ScriptableMember] attribute. e.g.: [ScriptableMember] public void CreateCircle(string pkID, string colorValue, string X_Y)
{
}
Step2:In the Application_Startup event 0f App.xaml.cs we have to call RegisterScriptableObject that will register a managed object for scriptable access by Javascript code.e.g.: private void Application_Startup(object sender, StartupEventArgs e) { HtmlPage.RegisterScriptableObject(“Common”, new Common());
}
The first parameter is a key(any name that you want to give)through which the function will be accessed from java script.
It is the name used to register the managed object.
And the second parameter is the instance of the class i.e. the managed object where the function presents(in this case its Common in side which the function
CreateCircle presents)
Step3:Accessing the function from java script. e.g.: var slObject = $find(“”); var slElement = pluginObject.get_element();
slElement.Content.Common.CreateCircle(pkId, colorValue, X_Y);
Where slBodyImage is the id of the silverlight control in the aspx page
Common is the name of the key