• Silverlight.FX
    Silverlight.FX is a light-weight application framework for building RichInternet Applications with Silverlight 2.
  • Building Modular Silverlight Applications
  • .NET RIAServices - Building Data-Driven Applications with Microsoft Silverlight andMicrosoft ASP.NET
  • Securing Silverlight Application and WCF Service using ASP.Net Authentication Techniques
  • Model– View – ViewModel in Silverlight
Skip Navigation LinksHome / Articles / View Article

Did You Know That... The Code Behind is Just... Code?

+ Add to SilverlightShow Favorites
0 comments   /   aggregated from Jesse Liberty - Silverlight Geek on Feb 03, 2008  /  original article
(0 votes)
Categories: Tips and Tricks

A very insightful reader sent me email that I'm going to respond to here. To protect his identity let's call him Bob. I'm going to excerpt Bob's  email and rephrase a bit so that this becomes a more general discussion.

I find that a lot of Webcasts and books about Silverlight spend most of their time explaining XAML or using Expression tools in  great depth, yet whenever its time to examine the code,  the presenter tends to speed up and glide over the actual JavaScript.

...I noticed in your last Webcast you made the comment that you would be spending most of the hour talking code, ...however, once again lots of time was spent on XAML shapes and gradiant fills, but when it came to the actual code behind side, that was rapidly glossed over....I get the feeling that a lot of people are really enthusiastic about Silverlight, however they are perhaps lacking the "JavaScript 101 for Silverlight" that is needed to follow along with most of the webcasts.

Bob went on to observe that switching rapidly between Visual Studio and IE in Live Meeting is not a great tactic (one I will solve next time by setting up my desktop properly, and then sharing the entire desktop to avoid all the switching).

I think Bob's key point is exactly right, and while I can't answer for anyone else, I can tell you why this happens in my presentations; though now that it has been pointed out to me, I have the opportunity to make a conscious decision to change.

First, in a course named "Getting started with..." or "from scratch" there seems to be an imperative to spend a good bit of time showing where the resources are. That can be very time consuming. It might be better to point folks to our web site and to my How Do I Get Started? web post and let it go at that.

The second reason is more pressing, and it is that Silverlight 1.0 has  always been about XAML and code-behind, but the code behind has always been, if I'm going to be totally honest, "well, it's JavaScript right now, but it should be C# and it will be C#, so let's just show how the logic works without dwelling on the implementation which is, after all, not object oriented or the way we'll do things in the long run."

Now, there are a couple real problems with that attitude. 

First, Silverlight 2 won't be released (RTM) for quite a while. We'll be in Beta with a Go-Live license very soon, but it won't be replacing 1.0 until it is released. We've not announced a release date. Which means 1.0 isn't going away next week. So glossing over coding in 1.0 is a mistake.

Second, you can still code in JavaScript if you want to in 2.0 and some folks will most certainly want to (Calling all AJAX programmers).

Most important, if you are going to teach Silverlight From Scratch, then you can't gloss over the implementation of the code behind (read, in most cases, the event handlers) because you run the risk (read certainty) of leaving your users hopelessly confused and frustrated.  It all becomes a hand-wave, and even worse, the critical distinction between the XAML file and its code-behind becomes even more confusing. So I must stop this madness.

Hooking Up the Event Handlers

In the figure, Scene.xaml declares a Canvas and declares that the Canvas (which will hold a diamond) will respond to three known events: MouseLeftButtonDown, MouseLeftButtonUp, and MouseMove. The three functions that will serve as event handlers are named: OnMouseDown, OnMouseUp and OnMouseMove respectively.  

These Event handlers do not exist in the XAML file. They exist in the code-behind file: Scene.xaml.js

Note that the programmer could have named the functions Moe Larry and Curly; as long as the names match in the XAML declaration and the code-behind file, all is good.

This is where I wave my hands at the JavaScript and move on. So, why? 

JavaScript isn't that hard, though I will tell you that you'll run into two basic approaches when you review example code here and elsewhere. One, as shown here is the older style of independent functions and global variables. Perfectly respectable. The other, more object-oriented-ish creates kinda-sorta-member methods with kinda-sorta-member variables. That looks more like this:

In this example (which is what Visual Studio 2008 creates as a sample for you when you make a new Silverlight app) the prototype acts as a "class" and each function acts as a "method."  Any variable prepended with "this" is a member, declared with var is local.  In this style it is more common to wire up even handlers using addEventListener in the code rather than in the XAML.  More about this approach here.

It's Just Code

Returning to our story, already in progress, we had three event handlers: onMouseDown, onMouseMove and onMouseUp.

Each of these is just JavaScript, the kind you can find incredibly well described here in David Flanagan's book, BLOCKED SCRIPT The Definitive Guide:

BLOCKED SCRIPT The Definitive Guide
by David Flanagan

Read more about this title...

The code behind begins by declaring three variables that will be used by the event handlers.  The job of OnMouseDown is to store the location of the mouse by calling GetPosition on the mouseEventArgs argument passed in with the syntax shown. We then set trackingMouseMove to true (to signal to OnMouseMove that we are tracking a moving object) and we tell the sender (the object that caused the event) to "capture" the mouse, so that if we move off that object we'll still get mouse move events until the user lets the mouse button up.

As the user moves the mouse we check to see if we are tracking. If so, we continually recompute the new position of the mouse and then recompute the new position of the object, setting its Canvas.Left and Canvas.Top properties and then resetting the new values for the global  beginX and beginY

Finally, when the user lets the left mouse button up, we stop tracking and we tell the object to "uncapture" the mouse.

Not so bad.  Other than the manipulation of currentX vs BeginX in MouseMove the logic is fairly intuitive, and the syntax should feel pretty familiar to anyone who has worked in the C/Java family of languages.

All of this is walked through in great detail in this video and its example code.

Accessing XMAL defined objects in Code

Since I'm up late, and on a roll, let me mention one more bit about the relationship between XAML and the code behind; and that is how you access an object declared in XAML from your Javascript. The key to making this work is

  1. Name the object in XAML
  2. Use FindName to assign the object to a variable in the code behind

The XAML file:

Referring to these objects in code can be done in a number of ways, but it typically involves calling FindName, passing in the name used in the XAML as a string, and returning the reference to an object in the code:

Note that plugIn is the Silverlight Control which is passed in as the first parameter to hanldeLoad.  If you are not in handleLoad you can always get a reference to the Silverlight control by calling GetHost() as explained here.

Of course there's more to say, but this is a start on addressing the well made point that understanding the Javascript is an essential point in understanding how the Silverlight application works its magic.

Much thanks to "Bob"



Comments RSS RSS
No comments

Add Comment