With Silverlight, you can use simple code to implement interoperability between components such as Silverlight and HTML, and Silverlight and JavaScript. First, we must reference the namespace system. Windows. browser in the Silverlight and HTML interaction operations.
The following describes how to implement "Hello World.
I. HTML elements operated by Silverlight
1. First, modify the page title.
The following code can be added to the constructors on the Silverlight page:
Htmlpage. Document. setproperty ("title", "the title is seted by Silverlight ...");
2. Set the attribute values of HTML elements
1) Add a text box on the HTML page to be called by Silverlight, as shown below:
<Input id = "txtname" type = "text"/>
2) Add the following code to the constructors on the Silverlight page:
Htmlelement elementtxtshow = htmlpage. Document. getelementbyid ("txtshow ");
Elementtxtshow. setattribute ("value", "init name ");
3. Add events to HTML elements
1) Add a button to the HTML page as follows:
<Input id = "btnsayhello" type = "button" value = "Say hello"/>
2) use Silverlight to set server events for it
Htmlelement btnsetname = htmlpage. Document. getelementbyid ("btnsayhello ");
Btnsetname. attachevent ("onclick", delegate (Object sender, htmleventargs he)
{
Htmlelement element = htmlpage. Document. getelementbyid ("txtshow ");
Element. removeattribute ("value ");
Element. setattribute ("value", "Hello world! ");
});
Summary code. The following elements need to be added to HTML:
<Object ID = "silverlightcontrol" Data = "data: Application/x-silverlight-2," type = "application/x-silverlight-2"
Width = "100%" Height = "100%">
<Param name = "Source" value = "clientbin/*. xap"/>
<Param name = "onerror" value = "onsilverlighterror"/>
<Param name = "background" value = "white"/>
<Param name = "minruntimeversion" value = "4.0.50826.0"/>
<Param name = "autoupgrade" value = "true"/>
<A href = "http://go.microsoft.com/fwlink? Linkid = 149156 & V = 4.0.50826.0 "style =" text-Decoration: none ">
Style = "border-style: none"/>
</A>
</Object>
<Input id = "btnsayhello" type = "button" value = "Say hello"/>
<Input id = "txtshow" type = "text"/>
The following is the C # code of Silverlight. Add it to the constructor.
Htmlpage. Document. setproperty ("title", "the title is seted by Silverlight ...");
Htmlelement elementtxtshow = htmlpage. Document. getelementbyid ("txtshow ");
Elementtxtshow. setattribute ("value", "init text ");
Htmlelement btnsetname = htmlpage. Document. getelementbyid ("btnsayhello ");
Btnsetname. attachevent ("onclick", delegate (Object sender, htmleventargs he)
{
Htmlelement element = htmlpage. Document. getelementbyid ("txtshow ");
Element. removeattribute ("value ");
Element. setattribute ("value", "Hello world! ");
});
Next, the article introduces how to call Silverlight through JavaScript.