Friday, May 04, 2007

A common problem many people have been running into when creating Silverlight 1.0 projects is creating reusable controls, and for that matter using Silverlight's Downloader object in a clean fashion.

Here's a simple example that I threw together for some folks internally that's a great intro to object-oriented Javascript and general tutorial for using the Downloader while avoiding global event handlers.

New in the Silverlight 1.0 Alpha is function addEventListener on elements which allows functions to be added as event handlers instead of method names. Combined with a delegate function, which all AJAX frameworks provide and is provided in the default Expression Blend templates, the event callbacks can go straight to the object.

A very simple example using the event listeners is:
function Button(element) {
this.element = element;
element.addEventListener("mouseleftbuttondown",
Sys.Silverlight.createDelegate(this, this.handleMouseDown));
}

Button.prototype.handleMouseDown = function(sender, e) {
var pt = e.getPosition(this.element);
alert("Mouse clicked at: " + pt.x + "," + pt.y);
}

new Button(control.findName("RootElement"));

The Button object isn't a framework element itself, but it acts as a wrapper and adds the button functionality to the underlying visuals.

Sample code that shows using the downloader: Button.xaml.js
Sample code that shows using the button: Scene.xaml.js

The running sample.