Este articulo busca presentar los beneficios de la programación Javascript orientada a objectos para diseñar aplicaciones Silverlight. Este articulo no es una introducción a Silverlight, XAML, ó Javascript. Para una introducción a Silverlight y sus diferentes modelos de programación les exhorto a que visiten el sitio de comunidad de Silverlight de Microsoft.
Problema
La implementación de la funcionalidad 'Drag and Drop' es una de la manera mas sencilla en la que se puede mejorar una aplicación básica Silverlight 1.0 RC. Microsoft nos describe el proceso de implementación paso a paso en MSDN (presione aquí). Sin embargo, cuando se comienza a desarrollar una interfaz de usuario relativamente compleja en Silverlight, uno nota que va a tener que re-escribir todo este código para cada uno de los elementos que componen la interfaz de usuario que requieran esta funcionalidad.
Solución
Javascript nos permite diseñar codigo re-utilizable utilizando tecnicas de programación orientada a objetos. Nuestro objetivo es re-factorizar todo el codigo relacionado al proceso de 'Drag and Drop' en un componente re-utilizable una clase en javascript.
Acción
Comencemos por describir los elementos del XAML que vamos a mejorar mediante la implementación del 'Drag and Drop'. Como puede ver en la siguiente imagen, el XAML consiste de dos diferentes elementos un rectangulo y un "TextBlock" que colocados uno encima de otro dan la apariencia de un "Label". Adicionalmente, tenemos un rectangulo adicional que servira como punto de inicio del proceso de "Drag and Drop".

Visualización del XAML:

Si quisieramos implementar "Drag and Drop" utilizando las técnicas descritas en MSDN, tendriamos que manejar los siguientes eventos:
1. MouseLeftButtonDown: Utilizando el captureMouse method para obtener acceso exclusivo a todos los eventos relacionados al mouse. Adicionalmente, persistir la posición original del mouse. Finalmente, habilitar una variable booleana (flag) que marque el inicio del proceso de drageo.
2. MouseMove: Utilizar la posición original del mouse y la nueva para relocalizar el elemento dentro de su contenedor. Adicionalmente, persistir la posición actual del mouse como la original.
3. MouseLeftButtonUp: Soltar el control exclusivo de los eventos del Mouse utilizando el metodo releaseMouseCapture. Finalmente, pasar un valor de falso a la variable que marca el inicio del proceso de drageo.
El siguiente es el código,

Nuevamente, este proceso es relativamente sencillo, pero si quisieramos añadir esta misma funcionalidad a elementos adicionales, encontrariamos que tendriamos que reescribir todo el código una y otra vez para cada elemento nuevo. Esto obviamente es una señal clara que que se debe re-factorizarse inteligentemente el código actual.
Después de un poco de trabajo el resultado de re-factorización, y encapsulación produjo el siguiente código.

Esta clase Javascript resuelve dos problemas que se presentan en el desarrollo de aplicaciones Silverlight:
1.- Permite a desarrolladores habilitar la funcionalidad de "Drag and Drop" con solo una ó dos lineas de código.
2.- Adicionalmente, provee metodos adicionales para calcular las posición absoluta, o en otras palabras, la posición con relación al Canvas que es el elemento raiz del Xaml.
El siguiente código nos permite visualizar la funcionalidad implementada.

Se puede bajar el código incluido en este posteo. O pueden navegar los ejemplos en linea RHPConsulting.NET Silverlight Demos.
Gracias por leer,
____________________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE - Plus Father of Two
"Execution is the key to success
__________________________________________________________________
This article is meant to show the benefits of sound Javascript programming with your Silverlight Applications. It is not an introduction to Silverlight, XAML or Javascript. For an introduction to Silverlight, and its programming object model visit the Silverlight quickstarts.
Problem
Drag and Drop interaction is one of the simplest ways you can improve your basic Silverlight 1.0 RC application. Microsoft has a great sample on MSDN, that shows you how to implement it step by step (click here). However, once you start building a fairly complex Silverlight user interface, you come to the realization that you’re going to have to re-write this code over and over again for every single element on your canvas that you're going to want to enable drag and drop functionality for.
Solution
Javascript allows us to design re-usable code using object oriented techniques. So our goal should be to re-factor all code related to the dragging and dropping interaction into a re-usable javascript class.
Action
Lets start by describing the elements of a simple XAML file that we will be enabling drag and drop functionality for. As you can see in the following code snippet, the xaml has two visual elements defined within it, a rectangle and a textblock that is layered on top of the rectangle, giving the illusion of a fancy label. Additionally, there is a small rectangle that we will be using as a handle where users will click to start the dragging process.

Rendering of XAML:

If we wanted to enable simple drag and drop functionality for this item (as described in MSDN). We would have to handle the following events, in order to perform the following tasks:
1. MouseLeftButtonDown: Use captureMouse method to capture all mouse related events to the element that fired the event. Additionally, persist original mouse coordinates. Finally, set flag to enable dragging.
2. MouseMove: Using original persisted coordinates relocate element to new location within its container. Additionally, persist current mouse coordinates as original.
3. MouseLeftButtonUp: Release exclusive mouse event handling using releaseMouseCapture method. Finally, set flag to disable dragging.
See the following snippet.

And again this a fairly simple operation but what if we wanted to add a second, or third element, in the Silverlight user interface that required additional drag and drop functionality. If we follow the current code pattern we would have to add additional handlers in the handleLoad method, and additional methods for every single element. For anybody who’s been involved in programming for more than 24 hours, this should be an obvious sign that some smart re-factoring needs to be done.
So I started refactoring and adding additional functionality to the original MSDN sample, and I came up with the following Javascript Class.

This Javascript Class solves two problems when developing Silverligth Aplications:
1.- It allows the programmer to enable drag and drop functionality to any Silverlight user interface element with just a couple of lines of code.
2.- It also provides helper methods to determine the Canvas.Top, Canvas.Left coordinates of any element related to its parents container (usually a Canvas), or to the Silvelight Host control.
The following is a code snippet for enabling drag and drop functionality for the original xaml user interface in the top of this post.

You can download all the code included in this post by downloading a VisualStudio 2005 Solution and Projects that is attached to this post. Additionaly, you can browse the samples online at RHPConsulting.NET Silverlight Demos.
Thank you for reading,
____________________
Roberto Hernández-Pou
MCAD MCSD.NET MCT MCDBA MCSE - Plus Father of Two
"Execution is the key to success