Welcome to RHPConsulting.NET Sign in | Join | Help

Silverlight Drag and Drop Javascript Class - RC

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

Published Thursday, August 09, 2007 12:00 AM by rhernandez
Filed Under: ,
Attachment(s): Silverlight.DragDropExtender.zip

Comments

# Silverlight 1.0 RC Drag and Drop

Friday, August 10, 2007 5:36 AM by Jonas Stawski's Blog
If any of you are interested in a Drag and Drop library for Silverlight 1.0 RC, please visit Roberto's

# Silverlight Drag and Drop Javascript Class - RC

Tuesday, August 21, 2007 4:23 PM by DotNetKicks.com
You've been kicked (a good thing) - Trackback from DotNetKicks.com

# Drag & Drop en Silverlight

Wednesday, August 22, 2007 6:10 PM by ricardoj's blog
Roberto Hernández Pou , un MVP de Puerto Rico, escribió un artículo en su blog sobre cómo realizar funcionalidad

# Drag & Drop en Silverlight

Wednesday, August 22, 2007 6:26 PM by Noticias externas
Roberto Hernández Pou , un MVP de Puerto Rico, escribió un artículo en su blog sobre cómo realizar funcionalidad

# MSDN Blog Postings » Drag & Drop en Silverlight

Wednesday, August 22, 2007 8:18 PM by MSDN Blog Postings » Drag & Drop en Silverlight

# August 30th Links: ASP.NET, ASP.NET AJAX, IIS7, Visual Studio, Silverlight, .NET

Thursday, August 30, 2007 12:40 AM by ScottGu's Blog
Here is the latest in my link-listing series . Also check out my ASP.NET Tips, Tricks and Tutorials page

# August 30th Links: ASP.NET, ASP.NET AJAX, IIS7, Visual Studio, Silverlight, .NET

Thursday, August 30, 2007 12:58 AM by Elan's Aggregated Blogs
Here is the latest in my link-listing series . Also check out my ASP.NET Tips, Tricks and Tutorials page

# August 30th Links: ASP.NET, ASP.NET AJAX, IIS7, Visual Studio, Silverlight, .NET

Thursday, August 30, 2007 1:07 AM by BusinessRx Reading List
Here is the latest in my link-listing series . Also check out my ASP.NET Tips, Tricks and Tutorials page

# August 30th Links: ASP.NET, ASP.NET AJAX, IIS7, Visual Studio, Silverlight, .NET

Thursday, August 30, 2007 1:11 AM by ASP.NET
Here is the latest in my link-listing series . Also check out my ASP.NET Tips, Tricks and Tutorials page

# Enlaces de Agosto: ASP.NET, ASP.NET AJAX, IIS7, Visual Studio, Silverlight, .NET « Thinking in .NET

# Silverlight 1.0 is out and it supports Linux

Tuesday, September 04, 2007 9:33 PM by Scott Hanselman's Computer Zen

# Silverlight 1.0 officially released

Tuesday, September 04, 2007 11:07 PM by dnknormark.net
Silverlight 1.0 officially released

# August 30th Links: ASP.NET, ASP.NET AJAX, IIS7, Visual Studio, Silverlight, .NET « Tuff Stuff

# Recursos para o aprendizado do MS Silverlight

Saturday, September 08, 2007 11:19 PM by Mutamblog
Recursos para o aprendizado do MS Silverlight

# August 30th Links: ASP.NET, ASP.NET AJAX, IIS7, Visual Studio, Silverlight, .NET at aoortic! dot com

# August 30th Links: ASP.NET, ASP.NET AJAX, IIS7, Visual Studio, Silverlight, .NET

Wednesday, October 03, 2007 8:03 PM by ASPInsiders
Here is the latest in my link-listing series . Also check out my ASP.NET Tips, Tricks and Tutorials page

# Silverlight 1.0 is out and it supports Linux

Tuesday, October 09, 2007 6:32 AM by Blogs
Wow, I didn't see this coming. ( That's a lie, I totally saw it coming and have been saying it

# http://community.rhpconsulting.net/blogs/rhpnetblog/archive/2007/08/09/24.aspx

# Silverlight 1.0 RC Drag and Drop

Friday, June 20, 2008 8:19 AM by Jonas Stawski
Silverlight 1.0 RC Drag and Drop

# Silverlight 1.0 RC Drag and Drop

Friday, June 20, 2008 8:23 AM by Jonas Stawski
Silverlight 1.0 RC Drag and Drop

# Silverlight 1.0 RC Drag and Drop

Friday, June 20, 2008 8:32 AM by Jonas Stawski
Silverlight 1.0 RC Drag and Drop

# Silverlight 1.0 RC Drag and Drop

Friday, June 20, 2008 8:43 AM by Jonas Stawski
Silverlight 1.0 RC Drag and Drop

# silverlight drag and drop

Thursday, June 26, 2008 5:48 AM by silverlight drag and drop

# Ultram.

Monday, July 07, 2008 4:40 PM by Ultram extended release.
Ultram. Ultram er. Do not take ultram with sudafed. Ultram erowid medicine. Ultram abuse.
Anonymous comments are disabled