Thursday, May 8, 2008

Silverlight - Javascript communication - Part 1

Please don't confuse this with one of my earlier post which described how to do things with javascript without disturbing C#.

Here I am going to say how to accomplish communication between C# code in Silverlight and Javascript in aspx , html or any file which hosts Silverlight plug in.

Simple communication
Here I am using the Invoke() method of HTMLWindow class for communication.
  • Silverlight –> Javascript The data flow here is from Silverlight to Javascript.For accomplishing this we need to entities.
    1. Sender->Silverlight code which initiate the action.This is Invoke() method call now.
    2. Receiver -> Javascript function which is being called by Silverlight's Invoke method
    Silverlight
    private void Button_Click(object sender, RoutedEventArgs e){
    System.Windows.Browser.HtmlPage.Window.Invoke("ShowMsg", txtInput.Text);

    }

    Javascript

    function ShowMsg(msg)
    {
    alert(msg);
    }



  • Javascript -> Silverlight

    Here the data flow is from Javascript to Silverlight.i.e we returns some value from the javascript function to Silverlight .

    Javascript

    function GetData()
    {
    var reply = prompt("What's your name?", "");
    return (reply);
    }


    Silverlight


    private void Button_Click_1(object sender, RoutedEventArgs e){
    string o=(string)System.Windows.Browser.HtmlPage.Window.Invoke("GetData", "");
    txtOutput.Text = o;
    }

Sample here

Here initiator of all the communications is Silverlight.But what to do if Javascript has to start communication.For that we should be familiar with Scriptable attribute,ScriptObject etc..That will discuss later otherwise this post become a story. :-)

Tuesday, May 6, 2008

Run Tag v/s code

As a Silverlight dev or designer, we are all familiar with Run tag which helps us to show multiple text formats in single TextBlock.

Normally we achieve the Run functionality through XAML.But have you think of doing the same from c#?? There is no direct children in TextBlock where we can pump objects of Run.
Then what to do ?

The solution is simple Use the TextBlock.Inlines collection.

Here goes the implementation

Run joy = new Run();

joyr.Text = "joy";

joy.Foreground = new SolidColorBrush(Colors.Blue);

Run george = new Run();

george.Text = "joy";

george.Foreground = new SolidColorBrush(Colors.Blue);


txt.Inlines.Add(joy);

txt.Inlines.Add(george);