Both are automatically generated when the Silverlight application is created:
I. Call the Silverlight background method in javascrpt
The key to calling is how to expose the background method (the method defined in Silverlight) to the client to facilitate JavaScript calls. After being exposed, the client accesses the Silverlight object and then finds the exposed background method.
1. Build a browser Bridge
Note: The code running on the HTML page uses the name myscript to access the Silverlight object. This is the entire HTML object.
2. Call the method written in the Silverlight object in HTML
- In test.html, we can easily find the <Object> mark, which is a Silverlight object, including parameters such as source, background, and onerror. This object is marked with ID = "silverlightobj ", in this way, the object can be accessed by ID in JavaScript.
<Object ID = "silverlightobj" Data = "data: Application/x-silverlight-2, "type =" application/x-silverlight-2 "width =" 100% "Height =" 100% "> <Param name =" Source "value =" clientbin/sbsch9_1.xap "/> <Param name =" onerror "value =" onsilverlighterror "/> <Param name =" background "value =" white "/> <Param name =" minruntimeversion "value =" 5.0.61118.0 "/> <Param name = "autoupgrade" value = "true"/> <a href = "http://go.micro Soft.com/fwlink /? Linkid = 149156 & V = 5.0.61118.0 "style =" text-Decoration: none "> </a> </Object>
Note: The type Property specifies the MIME type of the object to be loaded. For Silverlight applications, the MIME type application/x-silverlight-2 is used.
- Call the background Method
<script type="text/javascript"> function updatecity(country) { var slplugin = document.getElementById("silverlightobj"); slplugin.content.myscript.UpdateCities(country); } </script>
In this way, the Silverlight method is called in HTML.
Ii. Call the client's JavaScript method in the Silverlight Method
The key point is htmlpage. Window. getproperty ("movemap") as scriptobject to get the script object on the page.
This call is relatively simple, and the code is attached:
ScriptObject movemap = HtmlPage.Window.GetProperty("MoveMap") as ScriptObject;movemap.InvokeSelf(strcity);
Script on the HTML page:
<script type="text/javascript"> var map = null; function GetMap() { map = new VEMap('mapdiv'); map.LoadMap(); } function MoveMap(where) { try { map.Find(null,where); } catch (e) { alert(e.Message); } } </script>
Note: The getproperty parameter is the script method name.
Conclusion: In Silverlight, you can use HTML buttons to directly call the C # method. I tried to test a similar call in Asp.net, and eventually failed, on ASP.net, it is better to directly use server controls to communicate directly with the background method.