Silverlight Day 2

Posted Friday, February 22, 2008 8:53 PM by Kevin

Today's goal is to display an image and react to a mouse click in some way.  I actually started by reading the QuickStart that gets installed along with the Silverlight SDK.  You can also find it at if you still don't have the SDK installed (and why don't you?  Huh?)

It looks like all I need to display an image is an object set to fill with an ImageBrush.  Something like this should work:

<Ellipse Height="100" Width="200" Canvas.Top="10" Canvas.Left="10">


        <ImageBrush ImageSource="lolcat_quadcore.jpg" />



Bingo, that did the trick.  It looks like this:

lolcat ellipse

Oh wait, I just found the Image object - no brush needed if you do it like this:

<Image Source="lolcat_quadcore.jpg" Canvas.Top="120" Canvas.Left="10" Height="100" />

Which looks like this:

lolcat image

Note that in the first case, the image was automatically stretched to fit the dimensions of the ellipse and in the second, I only specified a height - so the image was automatically scaled proportionally.  Cool!

Now, processing mouse clicks.  This appears to be amazingly easy as well.  First, you need to declare the event handler in the XAML mark-up like this:

<Image Source="lolcat_quadcore.jpg" Canvas.Top="120" Canvas.Left="10" Height="100" MouseLeftButtonDown="ChangeLolcat" />

Then you just need a javascript function to handle the event - mine looks like this:

function ChangeLolcat( sender, args )


    if ( sender.Source == "lolcat_quadcore.jpg" )

        sender.Source = "lolcat_schroedinger.jpg";


        sender.Source = "lolcat_quadcore.jpg";


In this case, because the MouseLeftButtonDown event is on the Image object, that's the object that gets passed in to the javascript function as "sender".  I am simply changing the Source property from how it was defined in the XAML in response to the mouse click.  And it works! (sorry I can't show you - I don't have a good place to host .NET code at the moment)  I think I'm going to like working with Silverlight.

In case you want to download the code for this project and try it out yourself, I will ZIP it up and attach it to this blog post.

Filed under: , ,


No Comments