📜 ⬆️ ⬇️

Silverlight 2. Integration with HTML and JavaScript

Silverlighter
In the beginning I would like to share interesting news. We, with the support of creative designers from Samara Turbomilk, launched the alpha version of the Silverlight User Community - the site Silverlayter .

By the way, SilverLighter is not only a member of the community, but this remarkable creature with a gas glow in the picture :)

Well, now, actually, let's move on to the article itself.
Hello dear readers. My name is Sergey Pugachev. I have been a Silverlight developer for quite a long time and have been actively promoting this technology, so I am often asked about how to implement this or that feature or functionality. This article is a kind of answer to these frequently asked questions. This is the first part, it is devoted to issues of integration with HTML and JavaScript.
')

But let's start with a small marketing introduction.

Recently, Microsoft Silverlight technology is on everyone's lips. Various possibilities of the second version (Silverlight 2), published on October 14, 2008, are vividly discussed at forums and blogs. Many have already started writing Silverlight applications, and someone is going to start developing solutions using Silverlight technology in the very near future. The range of possible applications of this technology is huge. Here and online TV broadcasting, entertainment and educational portals. In my opinion, in the near future, full-fledged corporate (Line of Business, Enterprise, CRM and ERP) Silverlight applications will appear and actively develop. And the overwhelming majority of .NET developers with whom I spoke, like Silverlight technology. And it inspires some optimism! As they say, try and you.

If you are not familiar with Silverlight technology yet, I recommend that you first read the water articles and see the screencasts that you can find at http://www.silverlighter.ru and http://techdays.ru/ . And then move on to reading this article.

Well, dear readers, have you not thought to this place that ENOUGH this MARKETING already! Yes, indeed, for us, for developers, the main program, and not marketing statements. I promise that at this place all marketing ends and that which you and I love, namely CODE, begins.


So, here are some topics I would like to highlight in the first part of the article:


Creating a Silverlight project application


Let's create a new Silverlight application in Visual Studio 2008 SP1 with Silverlight Tools for Visual Studio installed. To do this, select File-> New-> Project-> Silverlight-> Silverlight Application. Name the application MySilverlightApplication and press the OK button. In the Add Silverlight Application dialog, we will keep the default values. Click OK and see two new projects in Visual Studio. Actually Silverlight application and ASP.NET application for hosting Silverlight application. Well, that you probably already know.

Read initialization parameters


Now we will do the following. We will set the initialization parameters for the Silverlight plugin on the pages MySilverlightApplicationTestPage.html and MySilverlightApplicationTestPage.aspx. After reading the Silverlight initialization parameters, the application will choose which XAML page to make as the starting page and accordingly show it to the user when loading: the default Page.xaml or the NextPage.xaml that we create.

To do this, add a new page to the Silverlight application. Right click on the project name, select Add-> New Item-> Silverlight User Control. Let's call the control NextPage.xaml. And press the OK button.

Next, we will change the background color of the NextPage page to red in order to determine the loaded page at runtime, because the background of the Page.xaml page will remain white. Set the Background property of the Grid element (named LayoutRoot) to the value “Red”.

Now open the MySilverlightApplicationTestPage.html page in the ASP.NET project and take a look at the Silverlight implementation code for the application:

< object data ="data:application/x-silverlight-2,"
type ="application/x-silverlight-2"
width ="100%" height ="100%" >
< param name ="source" value ="ClientBin/MySilverlightApplication.xap" />
< param name ="onerror" value ="onSilverlightError" />
< param name ="background" value ="white" />
< param name ="minRuntimeVersion" value ="2.0.31005.0" />
< param name ="autoUpgrade" value ="true" />
< a href ="http://go.microsoft.com/fwlink/?LinkID=124807"
style ="text-decoration: none;" >
< img src ="http://go.microsoft.com/fwlink/?LinkId=108181"
alt ="Get Microsoft Silverlight" style ="border-style: none" />
</ a >
</ object >

* This source code was highlighted with Source Code Highlighter .

Let's add the following tag inside the object tag:

< param name ="initParams" value ="startPage=Page" />

* This source code was highlighted with Source Code Highlighter .

This code sets the initialization parameter with the name “startPage”, the value of which is equal to “Page”. In this case, the parameter is one, but we can write several parameters separated by a comma.

Now open the ASP.NET page MySilverlightApplicationTestPage.aspx. The implementation code for the Silverlight application is different and looks like this:

< asp:Silverlight ID ="Xaml1" runat ="server"
Source ="~/ClientBin/MySilverlightApplication.xap"
MinimumVersion ="2.0.31005.0" Width ="100%" Height ="100%" />

* This source code was highlighted with Source Code Highlighter .

Change it to this code:

< asp:Silverlight ID ="Xaml1" runat ="server"
Source ="~/ClientBin/MySilverlightApplication.xap"
MinimumVersion ="2.0.31005.0" Width ="100%" Height ="100%"
InitParameters ="startPage=Page" />

* This source code was highlighted with Source Code Highlighter .

The changes made are obvious. InitParameters property added.

We used two equivalent, from the Silverlight point of view, applications for setting initialization parameters: for the object tag and for the asp: Silverlight server control.

Now we need to get the initialization parameters in the Silverlight application itself. To do this, open the C # code of the App.xaml page and replace the Application_Startup function code with the following:

private void Application_Startup( object sender, StartupEventArgs e)
{
string startPage = e.InitParams[ "startPage" ];
if (startPage != null && startPage.Equals( "Page" ))
{
this .RootVisual = new Page ();
}
else
{
this .RootVisual = new NextPage();
}
}

* This source code was highlighted with Source Code Highlighter .

The StartupEventArgs.InitParams property is of type IDictionary <string, string>. And we can get all the specified initialization parameters from this dictionary. In our case, if the startPage parameter we set is equal to “Page”, the control element described in the Page.xaml file becomes the main visual element of the application. For any other value, the NextPage.xaml page will be the main visual control of the application.

Let's run the program and look at the result. Change the value of the startPage parameter and see what happens. Do not forget, then return the value of the parameter back. Since we will use this Silverlight application for further examples.

Access to HTML DOM (Document Object Model)


In the first example, changes were made on two (HTML and ASP.NET) pages. Later in the article, to debug Silverlight applications only the page will be used - MySilverlightApplicationTestPage.aspx and all changes will be made accordingly only on it.

To access the HTML document of the page that hosts the Silverlight application, use an HtmlPage.Document object of type HtmlDocument. Also do not forget to connect the namespace System.Windows.Browser. To do this, add the following section to the usings section of the C # Page.xaml.cs file:

using System.Windows.Browser

* This source code was highlighted with Source Code Highlighter .

Let's now add a button to the Page.xaml page, which will have the name “mainButton”, and set the button press event. Here is the source code of the page:

< UserControl x:Class ="MySilverlightApplication.Page"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
Width ="400" Height ="300" >
< Grid x:Name ="LayoutRoot" Background ="White" >
< Button Click ="Button_Click" Content =" "
Width ="250" Height ="50" x:Name ="mainButton" />
</ Grid >
</ UserControl >

* This source code was highlighted with Source Code Highlighter .

Open the MySilverlightApplicationTestPage.aspx page in an ASP.NET application and look at the Silverlight implementation code for the plugin.

< div style ="height:100%;" >
< asp:Silverlight ID ="Xaml1" runat ="server"
Source ="~/ClientBin/MySilverlightApplication.xap"
MinimumVersion ="2.0.31005.0" Width ="100%" Height ="100%"
InitParameters ="startPage=Page" />
</ div >

* This source code was highlighted with Source Code Highlighter .

The asp: Silverlight tag is inside a div tag. Give the div the name “myDIV” and change the style.

< div id ="myDIV" style ="background:blue;width:100%;height:100%" >

* This source code was highlighted with Source Code Highlighter .

Also set the width for the Silverlight plugin, Width = "50%", not 100%.

< asp:Silverlight ID ="Xaml1" runat ="server"
Source ="~/ClientBin/MySilverlightApplication.xap"
MinimumVersion ="2.0.31005.0" Width ="50%" Height ="100%"
InitParameters ="startPage=Page" />

* This source code was highlighted with Source Code Highlighter .

Now we will write the code for the button click handler:

private void Button_Click( object sender, RoutedEventArgs e)
{
HtmlDocument doc = HtmlPage.Document;
HtmlElement div = doc.GetElementById( "myDIV" );
div.SetStyleAttribute( "background" , "green" );
}

* This source code was highlighted with Source Code Highlighter .

With this code we get the HTML document, find the element inside the HTML document and set the style for this element. Thus, inside the Silverlight application, we have rich possibilities for changing the appearance and content of the HTML page.

Moreover, we can handle HTML page events in our C # code. To do this, add a code to the button click handler, Button_Click:

div.AttachEvent( "onclick" , new EventHandler((o, x) =>
{
div.SetStyleAttribute( "background" , "yellow" );
}));

* This source code was highlighted with Source Code Highlighter .

We join the event of clicking on the free space of the div element. With this click, the background color changes to yellow. Here, a lambda expression is used for the event handler. Here is the complete code for the button click handler:

private void Button_Click( object sender, RoutedEventArgs e)
{
HtmlDocument doc = HtmlPage.Document;
HtmlElement div = doc.GetElementById( "myDIV" );
div.AttachEvent( "onclick" , new EventHandler((o, x) =>
{
div.SetStyleAttribute( "background" , "yellow" );
}));
div.SetStyleAttribute( "background" , "green" );
}

* This source code was highlighted with Source Code Highlighter .

Since this is a test example, each time you press the button, the event is signed. In real applications, it is impossible to do this and it is necessary to bring this code to the initialization section. For example:

public Page ()
{
InitializeComponent();
HtmlDocument doc = HtmlPage.Document;
HtmlElement div = doc.GetElementById( "myDIV" );
div.AttachEvent( "onclick" , new EventHandler((o, x) =>
{
div.SetStyleAttribute( "background" , "yellow" );
}));
}

private void Button_Click( object sender, RoutedEventArgs e)
{
HtmlDocument doc = HtmlPage.Document;
HtmlElement div = doc.GetElementById( "myDIV" );
div.SetStyleAttribute( "background" , "green" );
}

* This source code was highlighted with Source Code Highlighter .

Here we are in the page constructor subscribing to the event we need.
Run this application. Press the button. The blue space will turn green. Now click on the green space and it will turn yellow.

It should be noted that you can deny access to the HTML page from the Silverlight application. To do this, set the HtmlAccess = "Disabled" property on the asp: Silverlight server control. Whether access to the HTML page and scripts is allowed can be checked from the Silverlight application through the HtmlPage.IsEnabled property.

Calling JavaScript functions from Silverlight


Now let's talk about JavaScript integration. To call a JavaScript function from Silverlight, just write the following code:

HtmlPage.Window.Invoke( "DisplayMessage" , " Silverlight!" );

* This source code was highlighted with Source Code Highlighter .

Here we call the JavaScript function DisplayMessage and pass it as a parameter string. Add this code to the button event handler.

Now create this JavaScript function on the ASP.NET page. Section head page will look like this:

< head runat ="server" >
< title > MySilverlightApplication </ title >
< script type ="text/javascript" >
function DisplayMessage(message) {
alert(message);
}
</ script >
</ head >

* This source code was highlighted with Source Code Highlighter .

After that, when you click on the button, the JavaScript function is performed. Which displays a message with the specified text. The message text is passed in the parameter. Run the application and check its work.

Calling Silverlight functions from JavaScript


Now it's time to call functions from JavaScript in our Silverlight application. To do this, set the ScriptableType attribute on the Page type in the Page.xaml.cs file.

[ScriptableType]
public partial class Page : UserControl

* This source code was highlighted with Source Code Highlighter .

This will allow us to access the specially marked functions of this object from JavaScript. But first we need to register the Page object as available for the call. To do this, add the following code to the Page () constructor:

HtmlPage.RegisterScriptableObject( "silverlightApplication" , this );

* This source code was highlighted with Source Code Highlighter .

Here we set the name (“silverlightApplication”) by which we can access the .NET object from JavaScript.

Now inside the Page class we need to create a function, which we will call from JavaScript. Here is the code for this function. It has the ScriptableMember attribute, which means that it can be called from scripts.

[ScriptableMember]
public void ChangeButtonContent( string text)
{
mainButton.Content = text;
}

* This source code was highlighted with Source Code Highlighter .

This function sets the text on the button on the Silverlight page.

The following is the complete code for the Page class:

[ScriptableType]
public partial class Page : UserControl
{
public Page ()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject( "silverlightApplication" , this );
HtmlDocument doc = HtmlPage.Document;
HtmlElement div = doc.GetElementById( "myDIV" );
div.AttachEvent( "onclick" , new EventHandler((o, x) =>
{
div.SetStyleAttribute( "background" , "yellow" );
}));
}

private void Button_Click( object sender, RoutedEventArgs e)
{
HtmlDocument doc = HtmlPage.Document;
HtmlElement div = doc.GetElementById( "myDIV" );
div.SetStyleAttribute( "background" , "green" );
HtmlPage.Window.Invoke( "DisplayMessage" , " Silverlight!" );
}

[ScriptableMember]
public void ChangeButtonContent( string text)
{
mainButton.Content = text;
}
}

* This source code was highlighted with Source Code Highlighter .

And the Page.xaml file:

< UserControl x:Class ="MySilverlightApplication.Page"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml"
Width ="400" Height ="300" >
< Grid x:Name ="LayoutRoot" Background ="White" >
< Button Click ="Button_Click"
Content =" "
Width ="250" Height ="50" x:Name ="mainButton" />
</ Grid >
</ UserControl >

* This source code was highlighted with Source Code Highlighter .

Now, change the JavaScript function of the DisplayMessage so that it calls the C # function ChangeButtonContent.

function DisplayMessage(message) {
alert(message);
silverLightControl = document.getElementById( "Xaml1" );
silverLightControl.content.silverlightApplication.ChangeButtonContent(
message);
}


* This source code was highlighted with Source Code Highlighter .

We get the Silverlight object of the plugin and call the ChangeButtonContent function, passing it the same parameter that we passed from the C # code to the DisplayMessage function.

The full code for the MySilverlightApplicationTestPage.aspx page is below:

<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Register Assembly="System.Web.Silverlight"
Namespace="System.Web.UI.SilverlightControls"
TagPrefix="asp" %>


<! DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

< html xmlns ="http://www.w3.org/1999/xhtml" style ="height:100%;" >
< head runat ="server" >
< title > MySilverlightApplication </ title >
< script type ="text/javascript" >
function DisplayMessage(message) {
alert(message);
silverLightControl = document .getElementById( "Xaml1" );
silverLightControl.content.silverlightApplication.ChangeButtonContent(
message);
}
</ script >
</ head >
< body style ="height:100%;margin:0;" >
< form id ="form1" runat ="server" style ="height:100%;" >
< asp:ScriptManager ID ="ScriptManager1" runat ="server" ></ asp:ScriptManager >
< div id ="myDIV" style ="background:blue;width:100%;height:100%" >
< asp:Silverlight ID ="Xaml1" runat ="server"
Source ="~/ClientBin/MySilverlightApplication.xap"
MinimumVersion ="2.0.31005.0" Width ="50%" Height ="100%"
InitParameters ="startPage=Page" />
</ div >
</ form >
</ body >
</ html >

* This source code was highlighted with Source Code Highlighter .

Run the application and check its performance.

Silverlight app
When you click a button in the Silverlight application, the background color of the div element on the HTML page changes, and the JavaScript function of the DisplayMessage function is invoked, which displays a message. This JavaScript function calls the C # function ChangeButtonContent in the Page class. The ChangeButtonContent function changes the text on the button.

This concludes the first part of the article. The following sections will highlight other relevant Silverlight application development issues. I will be glad to your wishes and comments.

Source: https://habr.com/ru/post/46501/


All Articles