Moving from a Silverlight 1.0 JavaScript mindset to a Silverlight 1.1 C# mindset isn't terribly difficult, but there are little traps here and there. For example, to download and display an image, you need to create and configure a Downloader object.
In JavaScript:
var downloader = this.control.createObject("downloader");
downloader.addEventListener("completed",
Silverlight.createDelegate(this, this._onDownloaderComplete));
downloader.open("GET", "YodaDog.jpg");
downloader.send();
In C#:
Downloader download = new Downloader();
download.Completed += new EventHandler(download_Completed);
download.Open("GET", new Uri("YodaDog.jpg", UriKind.Relative));
download.Send();
The obvious differences are the wiring of events and construction of the Downloader object. However, the basic patterns in the code are true to their environments and easy to remember. It's the little things that bite you, for instance the Uri passed into the downloader. If the C# version looked like this:
download.Open("GET", new Uri("YodaDog.jpg"));
… then it still compiles and looks like its JavaScript counterpart, but unfortunately doesn't work. We have to explicitly tell the Uri constructor we are passing a relative URI.
The code for getting the downloaded image into an Image control is almost identical.
JavaScript:
_onDownloaderComplete: function(sender, eventArgs)
{
this._mainImage.SetSource(sender, "");
}
C#:
void download_Completed(object sender, EventArgs e)
{
this._mainImage.SetSource((Downloader)sender, "");
}
Presto! Yoda dog appears:
But what if we want to take Yoda dog off the screen? The following JavaScript works:
Edit - Oops! The wrong code was pasted here, but is now fixed.
onMouseButtonUp: function(sender, eventArgs)
{
this._mainImage.source = null;
},
But the equivalent C# code will leave Yoda dog on the screen*.
void Page_MouseLeftButtonDown(object sender, MouseEventArgs e)
{
this._mainImage.Source = null;
}
Instead, an empty URI is needed:
void Page_MouseLeftButtonDown(object sender, MouseEventArgs e)
{
this._mainImage.Source = new Uri("", UriKind.Relative);
}
Of course, the XAML remains the same in both environments.
* Just look at the expression on the dog's face. You know what she is thinking? She's thinking: "Tonight, my owner's favorite shoes become a shredded pile of wet leather…".
Posted
Oct 10 2007, 11:18 AM
by
scott-allen