Learning Silverlight - part 1
So I decided to learn Silverlight. I figure it’d be nice to have experience with one of those RIA frameworks - Silverlight, JavaFx, AIR - and Silverlight seems the least evil to me.
My favorite way to learn a new language or framework or technology is to download a few simple examples and try to change them. Tutorials and books are nice, but real, working code has no equal. I started with a photo gallery from Design With Silverlight (which has plenty of other good examples). Load; compile; run. It does what I expect, and I see a few things I can change. But I won’t get into the boring details of what I did with the code, I’m just going to give an overview of how Silverlight works. All the snippits here are modified (simplified) versions of code from the photo gallery example.
A Silverlight app, at least version 1.0, consists of 3 parts: the HTML, the XAML, and the JavaScript. The HTML can be as simple as a div and a call to JavaScript function createSilverlight().
The XAML contains the descriptions of objects and animation in the canvas. Here are a couple examples:
This creates a 600×30 rectangle with a gradient so it’s black on the left, white on the right, and red in the middle. The MouseEnter and MouseLeave attributes define the JavaScript functions that will be called on their respective events. The Canvas.RenderTransform node sets the scale properties of the object. It’s needed in case we want to rescale the object.
This creates a storyboard (basically an animation) that will scale an object 1.5x over 1 second. DoubleAnimationUsingKeyFrames defines what property will be animated, and SplitDoubleKeyFrames defines the times and values.
The JavaScript contains the meat of the application (at least in this example). The most important piece is Silverlight.js, which is distributed by Microsoft and initializes the Silverlight objects. This will be the same in every app, and as far as we’re concerned for now it could be black magic.
Then there’s the app-specific code that does things like handle events.
This is the previously mentioned function called from the HTML page which will create the Silverlight object with the specified properties. Every app will have something like this.
This is the callback for the mouseEnter event, as specified in the first XAML snippit. It looks for the mouseEnter canvas object, defined in the second snippit, and calls begin to start the storyboard. Line 3 sets the target of the storyboard so it points to the same object that fired the event. So if you mouse-over the rectangle, it will call this function, which will run the storyboard and scale the rectangle.
That’s really all there is to getting started. Canvas objects are in the XAML with references to event callbacks. Animations are also in the XAML. And event handlers which can start animations and change object properties are in the JavaScript.