Document directory
- No parameter event
- Parameter event
- Basic type (the so-called primitive types)
- Complex types
This article summarizes the basic methods for interaction between Silverlight and HTML pages, including the method for js to call Silverlight, which is quite good.
The interaction between Silverlight and HTML pages is implemented by a group of types and Methods collectively referred to as HTML bridge. To enable the interaction function, you must specify the enablehtmlaccess parameter as true when creating the Silverlight control. Otherwise, exceptions may occur when using many methods.
In the object tag creation method:
<param name="enableHtmlAccess" value="true" />
Silverlight directly controls html
In Silverlight, you can use the classes and methods in the system. Windows. browser namespace to operate HTML, mainly involving the following classes:
- Browserinformation-information about the browser and client operating system
- Htmldocument-HTML document in the browser
- Htmlelement-represents an HTML Element
- Htmlpage-provides methods to operate the DOM
- Htmlwindow-indicates the window in Javascript
Among them, the most important thing is the htmlpage class, which provides a set of static methods to obtain instances of other classes, such:
- Obtain browserinformation:
Browserinformation browserinfo = htmlpage. browserinformation;
- Obtain htmldocument:
Htmldocument = htmlpage. Document;
- Obtain htmlwindow:
Htmlwindow = htmlpage. window;
The following lists some common operations:
- Open the webpage in a new window:
Htmlpage. Window. navigate (New uri ("https://www.google.com"), "_ blank ");
- Modify the page title:
Htmlpage. Document. setproperty ("title", "New title ");
- Modify and retrieve page element attributes:
Htmlelement ELEM = htmlpage. Document. getelementbyid ("elem1 ");
ELEM. setattribute ("value", "Haha ");
String value = ELEM. getattribute ("value ");
- Register HTML element events:
ELEM. attachevent ("onclick", delegate (Object sender, htmleventargs he)
{
//...
});
- Call Silverlight methods/properties in Javascript
To call the Silverlight method from JavaScript, Silverlight must first register scriptableobject. This can be done by adding scriptabletypeattribute to the JS type to expose all attributes, methods, and events of the type. If only some Members are exposed, you can also mark only scriptablememberattribute for this Member (only scriptableattribute in previous versions ). This tag is very loose. As long as there are Scriptable members in the class, you can use the htmlpage. registerscriptableobject method to register this class so that it can be accessed by JS. For example:
Code [http://www.xueit.com]public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("Page", this);
}
[ScriptableMember]
public string Process(string arg)
{
return "Called from js: " arg;
}
}
On the HTML page, you can use the following JS Code to call the process method:
Code [http://www.xueit.com]function callSL() {
var slHost = document.getElementById("SilverlightControl");
var page = slHost.Content.Page;
alert(page.Process('param from js'));
}
Register the callsl method to the onclick of the button:
<input type="button" value="Call SL" onclick="callSL()" />
Click the run result as follows:
The Calling method of the Silverlight attribute is the same.
(Note: Here "silverlightcontrol" is the Silverlight Control ID, that is, the Silverlight OBJECT tag ID .)
- Javascript registers events in Silverlight with no parameters
In Silverlight, events are marked with scriptablememberattribute or the classes containing the events are marked with scriptabletypeattribute, and then registered with htmlpage. registerscriptableobject to access the events in JavaScript. For example, Silverlight exposes the following events:
public event EventHandler ButtonClicked;
In JS, you can use the following code to register the event:
Code [http://www.xueit.com]function onSilverlightLoad() {
var slHost = document.getElementById("SilverlightControl");
var page = slHost.Content.Page;
page.ButtonClicked = function () {
alert("Button clicked in SL.");
};}
When you click the button in Silverlight, the registered JS Code will be executed:
It is worth noting that this section of JS cannot be executed in the onload event of the page, because the Silverlight control may not be loaded yet and should be placed in the onload event of the Silverlight control. Add the onload parameter to the Silverlight Tag:
<param name="onLoad" value="onSilverlightLoad" />
Parameter eventThen there is a question about how to pass the event parameters. Many people on the Internet say that when a custom parameter is specified, it cannot be obtained in JS, prompting that the specified method or attribute is not supported, in fact, you only need to specify the eventargs class as scriptabletype (you can also specify the member as scriptablemember ). Example.
Event parameter class:
Code [http://www.xueit.com][ScriptableType]
public class ButtonClickedEventArgs : EventArgs
{
public string Message { get; set; }
}
Mainpage class:
Code [http://www.xueit.com]Public partial class mainpage: usercontrol
{...
Private void button_click (Object sender, system. Windows. routedeventargs E)
{// Trigger the buttonclicked event and input the event parameters
Onbuttonclicked (New buttonclickedeventargs () {message = "Message from SL ."});
}
# Region [buttonclicked event]
[Scriptablemember]
Public event eventhandler <buttonclickedeventargs> buttonclicked;
[System. Diagnostics. debuggerstepthrough]
Protected virtual void onbuttonclicked (buttonclickedeventargs E)
{
If (null! = Buttonclicked)
{
Buttonclicked (this, e );
}
}
# Endregion
}
Change the JS event handler function:
page.ButtonClicked = function (sender, args) { alert(args.Message);};
In this case, when you click the button in SL, the result is as follows:
It can be seen that event ARGs is successfully passed out.
Under the hoodSo far, the general needs have been basically met. In fact, whether it is calling the Silverlight method/attribute from JS, or registering a Silverlight event, the essential problem is how to pass the hosted object to Javascript, where there is a problem with the object marshal. Marshal follows the following principles:
- The managed type is passed to JavaScript by passing a reference.
- To pass the Javascript type into Silverlight, you must first perform a hosted encapsulation.
- If an error occurs during the process of transferring the hosted type marshal to Javascript, an invalidoperationexception is thrown.
- If an error occurs when JavaScript data is marshal into Silverlight, the Javascript caller will get an exception. The exception text describes the error.
Basic type (the so-called primitive types)
The following types are basic types that can be passed directly between Silverlight and JS without the need to mark scriptabletypeattribute or scriptablememberattribute:
Silverlight |
Javascript |
String |
String |
Null |
Null |
Boolean |
Boolean |
Datetime |
Date |
Char |
Single Character String |
Numeric type |
Double (back-and-forth conversion may cause precision and overflow issues) |
Enumeration |
Number |
Guid |
Formatted string |
In addition, the basic C # array or the type that implements the ilist interface can be directly converted to the array in Javascript. The idictionary type can also be directly converted to the dictionary in JavaScript.
When an array in Javascript is passed into Silverlight, it is generally converted to object []; dictionary is converted to dictionary <string, Object>.
Complex types
For complex types created by users, You need to mark scriptabletypeattribute or scriptablememberattribute so that it can be correctly passed to JavaScript.
For the marshal between Silverlight and JavaScript, the above only describes the most basic situations. I also don't want to do that kind of thing that looks at msdn. For more complex situations and various precautions, you can refer to Silverlight and JavaScript plualing on your own.