Quick Silverlight Tip: Communicating between two Silverlight objects on a single page
Today I'll show how two Silverlight objects (Silverlight applications) could communicate while been hosted on one page.
Earlier today I've seen some blog post by Joel Neubeck about Silverlight objects communication. The way Joel does it is pretty traditional, by providing some JavaScript functionality on host page to communicate with each Silverlight application.
I'll show slightly different approach: each Silverlight application will communicate directly with another (giving the fact, that the IDs of Silverlight applications on page could be provided to each application with initialization parameters. More info about initialization parameters for Silverlight application could be found here).
For simplicity lets assume we two Silverlight applications which are pretty the same:
and
The only difference in XAML is StackPanel's "Background" color.
Note: The Silverlight application could be totally different, I present here two simple application just as example of something what could be done.
Now lets see the code. First and Second applications differs only by the name it registers itself on page.:
[ScriptableType]
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
//First application
HtmlPage.RegisterScriptableObject("Xaml1", this);
//Second application
//HtmlPage.RegisterScriptableObject("Xaml2", this);
}
[ScriptableMember]
public void ExecuteCall(string msg)
{
output.Text = msg;
}
private void btn_Click(object sender, RoutedEventArgs e)
{
//Logic which will update another application with data inputed in TextBox
}
}
Now the interesting part - onClick event I'll get the instance of another applications object by its ID on page, and just execute its [ScriptableMember] function:
//First application
ScriptObject anotherSL = HtmlPage.Document.GetElementById("Xaml2") as ScriptObject;
//Second application
//ScriptObject anotherSL = HtmlPage.Document.GetElementById("Xaml1") as ScriptObject;
if (null != anotherSL)
{
//First application
((anotherSL.GetProperty("content") as ScriptObject).GetProperty("Xaml2") as ScriptObject).Invoke("ExecuteCall", new string[] { input.Text.ToString() });
//Second application
//((anotherSL.GetProperty("content") as ScriptObject).GetProperty("Xaml1") as ScriptObject).Invoke("ExecuteCall", new string[] { input.Text.ToString() });
input.Text = "";
}
The only difference here is also the name (string) of another Silverlight application, and probably the name (string) of function which we want to invoke.
We done: two Silverlight applications "talks" with each other without JavaScript code written
Sources here.
Enjoy,
Alex