Summary of the basic methods for interaction between Silverlight and HTML pages

Source: Internet
Author: User
ArticleDirectory
    • No parameter event
    • Parameter event
    • Basic type (the so-called primitive types)
    • Complex types

Now sl3/4 and HTML page interaction have changed a lot compared with the previous, refer to some information, you have organized it yourself.

The interaction function between Silverlight and HTML pages is calledHTML BridgeA set of types and methods. To enable the interaction function, you must specifyEnablehtmlaccessThe parameter is true. Otherwise, exceptions are thrown when many methods are used.

In the object tag creation method:

 
<ParamName= "Enablehtmlaccess"Value= "True"/>
Silverlight directly controls html

Available in SilverlightSystem. Windows. BrowserThe classes and methods in the namespace to operate HTML mainly involve the following classes:

    • Browserinformation-Information about browsers and client operating systems
    • Htmldocument-HTML document in the browser
    • Htmlelement-Represents an HTML element.
    • Htmlpage-Provides methods to operate the Dom.
    • Htmlwindow-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:
      BrowserinformationBrowserinfo=Htmlpage.Browserinformation;
    • Obtain htmldocument:
      HtmldocumentHtmldocument=Htmlpage.Document;
    • Obtain htmlwindow:
      HtmlwindowHtmlwindow=Htmlpage.Window;

The following lists some common operations:

  • Open the webpage in a new window:
    Htmlpage.Window.Navigate (NewUri(Https://www.google.com"),"_ Blank");
  • Modify the page title:
    Htmlpage.Document.Setproperty ("Title","New title");
  • Modify and retrieve page element attributes:
    HtmlelementELEM=Htmlpage.Document.Getelementbyid ("Elem1");
    ELEM.Setattribute ("Value","Haha");
    StringValue=ELEM.Getattribute ("Value");
  • Register HTML element events:
    ELEM.Attachevent ("Onclick",Delegate(ObjectSender,HtmleventargsHe)
    {
    //...
    });
Call Silverlight methods/properties in Javascript

To call the Silverlight method from JavaScript, Silverlight must first register scriptableobject. This can be done by addingScriptabletypeattributeIn this way, all attributes, methods, and events of this type are exposed. If only some Members are exposedScriptablememberattribute(In the past, only scriptableattribute was used ). This flag is very loose, as long as there are Members in the class that are Scriptable, you can useHtmlpage.The registerscriptableobject method is used to register this class so that it can be accessed by Js. For example:

Public partial classMainpage:Usercontrol{PublicMainpage () {initializecomponent ();Htmlpage.Registerscriptableobject ("Page",This);}[Scriptablemember]Public StringProcess (StringArg ){Return"Called from JS :"+ARG;
}
}

On the HTML page, you can use the following JSCodeCall the process method:

FunctionCallsl (){VaRSlhost = Document. getelementbyid ("Silverlightcontrol");VaRPage = slhost. content. page;Alert (page. Process ('Param from js'));}

Register the callsl method to the onclick of the button:

 
<InputType= "Button"Value= "Call sl"Onclick= "Callsl ()"/>

Click the run result as follows:

The Calling method of the Silverlight attribute is the same.

(Here"Silverlightcontrol"Is the Silverlight Control ID, that is, the object tag ID of Silverlight .)

Javascript registers events in Silverlight with no parameters

In Silverlight, the event usesScriptablememberattributeUsed to mark or include eventsScriptabletypeattributeMark and then useHtmlpage.Registerscriptableobject registers this class and can access this event in JavaScript. For example, Silverlight exposes the following events:

 
Public eventEventhandler Buttonclicked;

In JS, you can use the following code to register the event:

FunctionOnsilverlightload (){VaRSlhost = Document. getelementbyid ("Silverlightcontrol");VaRPage = 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:

 
<ParamName= "OnLoad"Value= "Onsilverlightload"/>
Parameter event

Then 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:

 
[Scriptabletype]Public classButtonclickedeventargs:Eventargs{Public StringMessage {Get;Set;}}

Mainpage class:

 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 hood

So 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:

& Lt; TD width = "135" valign = "TOP" & gt; null & lt;/TD & gt; & Lt; TD width = "302" valign = "TOP" & gt; null & lt;/TD & gt; & Lt; TD width = "135" valign = "TOP" & gt; Boolean & lt;/TD & gt; & Lt; TD width = "302" valign = "TOP" & gt; Boolean & lt;/TD & gt; & Lt; TD width = "135" valign = "TOP" & gt; datetime & lt;/TD & gt; & Lt; TD width = "135" valign = "TOP" & gt; char & lt;/TD & gt;
Silverlight JavaScript
string string
date
single character string
Number Type double (Conversion back and forth 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, please refer to them on your own.Silverlight and JavaScript logging aling.

------------

Refer:

    • Interaction between Silverlight and JavaScript
    • Interaction between Silverlight and JavaScript
    • HTML Bridge: interaction between HTML and managed code
    • Making Silverlight Scriptable by JavaScript
    • Silverlight and JavaScript logging aling
    • Adding Silverlight to a web page by using HTML or Javascript

------------

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.