Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Code Interaction in Silverlight

Posted by Ramani Sandeep on June 28, 2010


So far, you have seen how a Silverlight application can reach into the browser to perform navigation and manipulate HTML elements. The one weakness of this approach is that it creates tightly bound code–in other words, a Silverlight application that has hard-coded assumptions about the HTML elements on the current page and their unique IDs. Change these details in the HTML page, and the Silverlight code for interacting with them won’t work anymore.

One alternative that addresses this issue is to allow interaction between code, not elements.

For example, your Silverlight application can update the content of the HTML page by calling a JavaScript method that’s in the page. Essentially, the JavaScript code creates an extra layer of flexibility in between the Silverlight code and HTML content. This way, if the HTML elements on the page are ever changed, the JavaScript method can be updated to match at the same time and the Silverlight application won’t need to be recompiled. The same interaction can work in the reverse direction–for example, you can create JavaScript code that calls a Silverlight method that’s written in managed C# code.

In this article, we’ll learn how Silverlight can fire off JavaScript code,and how JavaScript code can trigger a method in your Silverlight application.

Calling Browser Script from Silverlight

Using the Silverlight classes in the System.Windows.Browser namespace, you can invoke a JavaScript function that’s declared in a script block. This gives you a disciplined, carefully controlled way for Silverlight code to interact with a page.

For example, assume you have this function defined in the <head> section of your HTML page:

<script type="text/javascript">
function changeParagraph(newText) {
var element = document.getElementById("paragraph");
element.innerHTML = newText;
}
</script>

To call this method, you need to use the HtmlWindow.GetProperty() method and pass in the name of the function. You receive a ScriptObject, which you can execute at any time by calling InvokeSelf().

ScriptObject script = (ScriptObject)HtmlPage.Window.GetProperty("changeParagraph");

When you call InvokeSelf(), you pass in all the parameters. The changeParagraph() function requires a single string paragraph, so you can call it like this:

script.InvokeSelf("Changed through JavaScript.");

Calling Silverlight Methods from the Browser

This process is a bit more involved. In order to make it work, you need to take the following steps:

  1. Create a public method in your Silverlight code that exposes the information or functionality you want the web page to use. You can place the method in your page class or in a separate class. You’ll need to stick to simple data types, like strings, Boolean values, and numbers, unless you want to go through the additional work of serializing your objects to a simpler form.
  2. Add the ScriptableMember attribute to the declaration of the method that you want to call from JavaScript.
  3. Add the ScriptableType attribute to the declaration of the class that includes the scriptable method.
  4. To expose your Silverlight method to JavaScript, call the HtmlPage.RegisterScriptableObject() method.

Provided you take all these steps, your JavaScript code will be able to call your Silverlight method through the <object> element that represents the Silverlight content region. However, to make this task easier, it’s important to give the <object> element a unique ID. By default, Visual Studio creates a test page that assigns a name to the <div> element that contains the <object> element (silverlightControlHost), but it doesn’t give a name to the <object> element inside. Before continuing, you should create a test page that adds this detail, as shown here:

<div id="silverlightControlHost">
<object data="data:application/x-silverlight,"
type="application/x-silverlight-2-b1" width="400" height="300"
id="silverlightControl">
...
</object>
<iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>
</div>

After you’ve named the Silverlight control, you’re ready to create the scriptable Silverlight method.

To create this example, you need the custom page class shown here. It includes a single scriptable method, which is registered when the page is first created:

[ScriptableType()]
public partial class ScriptableSilverlight: UserControl
{
  public ScriptableSilverlight()
  {
    InitializeComponent();
    HtmlPage.RegisterScriptableObject("Page", this);
  }
  [ScriptableMember()]
  public void ChangeText(string newText)
  {
    lbl.Text = newText;
  }
}

When registering a scriptable type, you need to specify a JavaScript object name and pass a reference to the appropriate object. Here, an instance of the ScriptableSilverlight class is registered with the name Page. This tells Silverlight to create a property named Page in the Silverlight control on the JavaScript page. Thus, to call this method, the JavaScript code needs to use the find the Silverlight control, get its content, and then call its Page.ChangeText() method.

Here’s an example of a function that does exactly that:

<script type="text/javascript">
function updateSilverlightText()
{
var control = document.getElementById("silverlightControl");
control.content.Page.ChangeText(
"This TextBlock has been updated through JavaScript.");
}
</script>

You can trigger this JavaScript method at any time. Here’s an example that fires it off when a paragraph is clicked:

<p onclick="updateSilverlightText()">Click here to change the Silverlight
TextBlock.</p>

Now, clicking the paragraph triggers the updateSilverlight() JavaScript function, which in turn calls the ChangeText() method that’s a part of your ScriptableSilverlight class.

Example : here

Hope this helps !!!

Jay Ganesh (.j.)

Shout it

About these ads

14 Responses to “Code Interaction in Silverlight”

  1. Code Interaction in Silverlight « Ramani Sandeep’s Blog…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  2. Calabonga said

    that’s realy cool! thanks!

  3. To learn .net, C#, Java, J2EE, Silverlight, Visual Basic, Asp .net with advanced concepts, you can visit http://advanceddotnettutorial.blogspot.com

  4. window regulators said

    I had no trouble navigating through all the tabs as well as related info.
    The site ended up being truly simple to access. Excellent job..

    Excellent Post.. I enjoy some of content in the post

  5. 7 osi layers…

    [...]Code Interaction in Silverlight « Ramani Sandeep's Blog[...]…

  6. Rutika Patel said

    how to install automatically silverlight on client pc when run silverlight application on client pc
    means client has no need install silverlight Application. it done automatically..

    • Ramani Sandeep said

      Hi Rutika, Its does not mean like that. It actually checks for silverlight client is installed or not and than if not than it show some msg and that “missing component” like some informative message. we can provide link to silvelight site where user can add plugin for it. Thats it. automatically it will not install.

      I hope Now this is clear. Thanks
      Sandeep Ramani

  7. Elana said

    My coder is trying to convince me to move to .net from PHP.

    I have always disliked the idea because of the costs.
    But he’s tryiong none the less. I’ve been using Movable-type on a variety of websites
    for about a year and am nervous about switching
    to another platform. I have heard fantastic things about blogengine.
    net. Is there a way I can import all my wordpress content into it?
    Any help would be greatly appreciated!

  8. abcd said

    This is really interesting, You’re a very skilled blogger. I’ve joined your feed and look forward to
    seeking more of your magnificent post. Also,
    I’ve shared your site in my social networks!

  9. Jamaal said

    Hi there to every single one, it’s truly a fastidious for me to go to see this web page, it contains precious Information.

  10. Ward said

    I personally blog as well and I’m publishing a little something comparable to this
    blog, “Code Interaction in Silverlight Ramani Sandeep’s Blog”.

    Do you mind if I actuallyuse a lot of of your personal suggestions?

    Regards -Marilynn

  11. Good day! Do you know if they make any plugins
    to protect agvainst hackers? I’m kinra paranoid about losing everything
    I’ve worked hard on. Any recommendations?

  12. Hello! This is my first visit to your blog! We are
    a group of volunteers and starting a new project in a community in the same niche.
    Your blog provided us beneficial information to work on. You
    have done a marvellous job!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 480 other followers

%d bloggers like this: