Tuesday, 27 November 2007

Basic Silverlight 1.0 (javascript) - Load another XAML

I keep things simple in this blog, because when I search on web, I would like to find simple explanations and examples, not a sophisticated one. I can write a sophisticated one once I know the basic.

It is easy to load another xaml onto the existing one -  if you have not use 1.1 before 1.0. Since I have developed 1.1 first, I actually found it confusing in the first place, anyway.

Here is a simple Page.xaml, named "Page", have a canvas, and a TextBlock:

<Canvas
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="970" Height="616"
Background="White"
x:Name="Page"
>
<TextBlock x:Name="RandomButton" Width="36.258" Height="14.1" TextWrapping="Wrap"
Canvas.Left="19.639" Canvas.Top="110.283">
<Run FontFamily="Arial" FontSize="12" FontWeight="Bold"
Foreground="#FFFFFFFF" Text="Random"/>
</TextBlock>
</Canvas>


In the javascript "code behind" I add an event listener to the RandomButton textblock. I want to load Random.xaml onto this page when I click on RandomButton.

if (!window.Trash)
window.Trash = {};

Trash.Page = function() {}

Trash.Page.prototype =
{
handleLoad: function(control, userContext, rootElement)
{
this.control = control;
this.root = control.content.findName("Page");
this.RandomButton = control.content.findName("HomeButton");
this.RandomButton.addEventListene("MouseLeftButtonUp",
this.Random_onMouseLeftButtonUp);
}
}


We are going to send request for the xaml, and add it to the page asynchronously after it is loaded.

Trash.Page.prototype.Random_onMouseLeftButtonUp = function(sender, e)
{
Control_Send(sender.getHost(), "Random.xaml");
}

function Control_Send(host, control_path)
{
var downloader = host.createObject("downloader");
downloader.addEventListener("completed", Control_DownloaderCompleted);
downloader.open("GET", control_path);
downloader.send();
}

function Control_DownloaderCompleted(sender, e)
{
var xamlItem = sender.getResponseText("");

var host = sender.getHost();
var page = host.content.findName("Page");
var control = host.content.createFromXaml(xamlItem, true);

page.children.Add(control);
}


That's it!

No comments:

Post a Comment