devxlogo

Robust, Reusable Drag-and-Drop Behavior in Silverlight

Robust, Reusable Drag-and-Drop Behavior in Silverlight

s the richness of Internet applications continues to grow through technologies such as Silverlight, AJAX, and Flash, the adoption of common desktop user interface (UI) paradigms within these applications continues to increase. The most obvious paradigm perhaps is drag-and-drop behavior.

Although simple drag-and-drop behavior is available through some Silverlight controls, Silverlight’s overall implementation lacks some of the finer points of the behavior available in WPF. However, by manipulating an element’s RenderTransform with attached behaviors, you can greatly increase the overall robustness and reusability of any drag-and-drop implementation.

Novel Implementations

Silverlight by default facilitates drag-and-drop support through the Thumb control in System.Windows.Controls.Primitives. The simplest approach for implementing drag-and-drop is to use the Thumb control and apply the appropriate ControlTemplate for your application’s look and feel.

In many cases, though, using a Thumb is not practical. Constantly “templating” a Thumb control is often cumbersome in XAML, and you must repeat the application logic for this behavior in every single area in which you use it. As an application grows, this requirement makes the application nearly impossible to maintain.

However, two novel implementations allow you to enable drag-and-drop behavior on any UIElement in a generic way. Here is the first implementation:

VerticalAlignment="Top" Fill="#FFC20707" Stroke="#FF000000"/>

The most important aspects of this implementation are the specific events (present on any UIElement) that enable a drag-and-drop implementation: MouseLeftButtonDown, MouseMove, and MouseLeftButtonUp. By adding handlers to these events on any UIElement, you can perform a simple drag-and-drop.

The second implementation looks like this:

private bool isDragging = false;private void DragStart(object sender, MouseButtonEventArgs args){   Shape draggable = sender as Shape;   if (draggable != null)   {      isDragging = true;      draggable.CaptureMouse();   }}private void DragDelta(object sender, MouseEventArgs args){   Shape draggable = sender as Shape;   if (draggable != null && isDragging)   {      Point currentPosition = args.GetPosition(null);      TranslateTransform transform = draggable.RenderTransform          as TranslateTransform;      if (transform == null)      {         transform = new TranslateTransform();         draggable.RenderTransform = transform;      }      transform.X = (currentPosition.X - draggable.Width / 2);      transform.Y = (currentPosition.Y - draggable.Height / 2);   }}private void DragComplete(object sender, MouseButtonEventArgs args){   Shape draggable = sender as Shape;   if (draggable != null)   {       isDragging = false;      draggable.ReleaseMouseCapture();   }}

As you can see, by affecting the control RenderTransform as opposed to Panel-specific layout parameters such as the Canvas.Top and Canvas.Left attached properties or Grid margins, you can move an element around in any container. While this approach is reusable for any UIElement, it does not allow you to reuse the application logic across different controls. For that, you need an implementation that uses attached behaviors.

Using Attached Behaviors

WPF and .NET 3.0 introduced the concept of a dependency property, that is, a property that would notify the owner (which must be a DependencyObject) when it is changed and allow the owner to execute a piece of application logic.

See also  Custom Java Web Development - The Heartbeat of Modern Web Development

There are essentially two types of dependency properties. The most commonly used is the dependency property itself, which is both set on and owned by the same dependency object using DependencyProperty.Register. The second type is an attached property, which you set using DependencyProperty.RegisterAttached. An attached property is set on a different type than the type that owns it.

Consider a simple attached property, Hover:

public static readonly DependencyProperty HoverProperty =    DependencyProperty.RegisterAttached(   "Hover",   typeof(Brush),   typeof(Hover),   new PropertyMetadata(null, OnHoverChanged));

By providing the event handler OnHoverChanged, you can provide some application logic that gets executed when you set that property in XAML:

private static void OnHoverChanged(DependencyObject obj,      DependencyPropertyChangedEventArgs args){   Border border = obj as Border;   if (border != null)   {      if(args.OldValue == null && args.NewValue != null)      {         border.MouseEnter += SetHoverBackground;         border.MouseLeave += SetNotHoverBackground;      }      else if(args.OldValue != null && args.NewValue == null)      {         border.MouseEnter -= SetHoverBackground;         border.MouseLeave -= SetNotHoverBackground;      }   }}

The code for OnHoverChanged simply adds handlers that change the background color of the object on MouseEnter, and reverts it to the original background color on MouseLeave. This simple piece of functionality is called an attached behavior. Attached behaviors are the core concept behind the reusable drag-and-drop implementation described in the following sections. Consider the attached property IsEnabled:

public static readonly DependencyProperty IsEnabledProperty =    DependencyProperty.RegisterAttached(   "IsEnabled",   typeof(bool),   typeof(SimpleDragDropBehavior),   new PropertyMetadata(false, OnIsEnabledChanged));

By registering OnIsEnabledChanged as the property changed event handler, you can subscribe to the same event handlers you used before:

private static void OnIsEnabledChanged(DependencyObject obj,    DependencyPropertyChangedEventArgs args){   UIElement dragSource = obj as UIElement;   bool wasEnabled = (args.OldValue != null) ? (bool)args.OldValue : false;   bool isEnabled = (args.NewValue != null) ? (bool)args.NewValue : false;   // If the behavior is being disabled, remove the event handler   if (wasEnabled && !isEnabled)   {      dragSource.MouseLeftButtonDown -= DragStart;   }   // If the behavior is being attached, add the event handler   if (!wasEnabled && isEnabled)   {      dragSource.MouseLeftButtonDown += DragStart;   }}

The property changed event handler for IsEnabled simply added handlers to the events used in the novel implementations demonstrated before. In this way, it is simple to reuse the behavior across any and all UIElements in your application. However, the novel implementation previously discussed has its own set of limitations that are not immediately obvious.

Tracking absolute position by calling args.GetPosition(null) does not accommodate a behavior that allows nested drag-and-drop. A better solution is one that calculates the drag delta iteratively. To work around this limitation, you can turn to private attached properties. When considered in the scope of an attached behavior, a private attached property is analogous to a private member variable or property. Your public attached properties are then also analogous to public properties. Because you are simply tracking the X and Y positions of your draggable element, you need only two private attached properties:

public static readonly DependencyProperty XProperty =    DependencyProperty.RegisterAttached(   "X",   typeof(double),   typeof(DragDropBehavior),   new PropertyMetadata(double.NaN));public static readonly DependencyProperty YProperty =    DependencyProperty.RegisterAttached(   "Y",   typeof(double),   typeof(DragDropBehavior),   new PropertyMetadata(double.NaN));

The default value of these properties is double.NAN to indicate that the object does not currently have a drag-and-drop position. This will be important later for resetting your draggable elements between drags. In addition to these private attached properties, you also need to know which container is your relative frame of reference. That is, you need to specify the origin point, (X,Y) = (0,0). To do that, you simply specify that your host is using another attached property:

public static readonly DependencyProperty IsHostProperty =      DependencyProperty.RegisterAttached(   "IsHost",   typeof(bool),   typeof(DragDropBehavior),   new PropertyMetadata(false));

You now have established the data necessary to perform your iterative tracking drag-and-drop behavior. All you need to do is implement the same three handlers you defined before: DragStart, DragDelta, and DragComplete. In DragStart, you can take most of the functionality you had before and repurpose it as a static method in your behavior class:

private static void DragStart(object sender, MouseButtonEventArgs args){   UIElement dragSource = sender as UIElement;              // Create the TranslateTransform that will perform your drag operation   TranslateTransform dragTransform = new TranslateTransform();   dragTransform.X = 0;   dragTransform.Y = 0;   // Set the TranslateTransform if it is the first time DragDrop is being used         dragSource.RenderTransform = (      dragSource.RenderTransform is TranslateTransform) ?       dragSource.RenderTransform : dragTransform;   // Attach the event handlers for MouseMove and MouseLeftButtonUp    // for dragging and dropping respectively   dragSource.MouseMove += OnDragDelta;   dragSource.MouseLeftButtonUp += OnDragComplete;   //Capture the Mouse   dragSource.CaptureMouse();}

This is not too far from what you had originally. You get your draggable item, set its RenderTransform, attach the appropriate event handlers, and capture the mouse. The DragDelta implementation is significantly different, however. Because you are now tracking mouse movements relative to the previously recorded position in a relative container, you need to:

  1. Find your host container.
  2. Calculate the current position in that container.
  3. Compare that position to the previously record position and determine the delta.
  4. Update the RenderTransform and your private attached properties, X and Y.
private static void DragDelta(object sender, MouseEventArgs args){   FrameworkElement dragSource = sender as FrameworkElement;   // Calculate the offset of the dragSource and update its TranslateTransform   FrameworkElement dragDropHost = FindDragDropHost(dragSource);         Point relativeLocationInHost = args.GetPosition(dragDropHost);   Point relativeLocationInSource = args.GetPosition(dragSource);   // Get the current position   double xPosition = GetX(dragSource);   double yPosition = GetY(dragSource);   // Calculate the delta from the previous position   double xChange = relativeLocationInHost.X - xPosition;   double yChange = relativeLocationInHost.Y - yPosition;   // Update the position if this is not the first mouse move   if (!double.IsNaN(xPosition))   {      ((TranslateTransform)dragSource.RenderTransform).X += xChange;   }   if (!double.IsNaN(yPosition))   {      ((TranslateTransform)dragSource.RenderTransform).Y += yChange;   }       // Update your private attached properties for tracking drag location   SetX(dragSource, relativeLocationInHost.X);   SetY(dragSource, relativeLocationInHost.Y);}

It’s important to note how the preceding implementation finds the relative host. To accomplish this, you simply search up the visual tree for the first element that has IsHost = true.

See also  Custom Java Web Development - The Heartbeat of Modern Web Development

New Implementation for DragComplete

Now that all the nuts and bolts are in place for DragStart and DragDelta, the only piece that remains is a new implementation for DragComplete. As with DragStart, the DragComplete implementation is not all that different from your novel implementation. The only notable difference is that in addition to removing your event handlers and releasing the mouse capture, you must also reset your private attached properties, X and Y, to indicate that the draggable item is no longer dragging:

private static void DragComplete(object sender,    MouseButtonEventArgs args){   UIElement dragSource = sender as UIElement;               dragSource.MouseMove -= DragDelta;   dragSource.MouseLeftButtonUp -= DragComplete;   // Set the X & Y Values so that they can be reset next MouseDown   SetX(dragSource, double.NaN);   SetY(dragSource, double.NaN);   // Release Mouse Capture   dragSource.ReleaseMouseCapture();}

This new iterative implementation overcomes the limitations outlined previously. It also allows for fluid mouse tracking within the container on MouseDown. In the novel implementation, you simply centered the mouse on the draggable item. In the above implementation, the mouse pointer will stay within the container wherever it is clicked.

public static FrameworkElement FindDragDropHost(   UIElement element){   DependencyObject parent = VisualTreeHelper.GetParent(element);   while (parent != null && !GetIsHost(parent))   {      parent = VisualTreeHelper.GetParent(parent);   }   return parent as FrameworkElement;}

Limitations and Extensibility

The drag-and-drop behavior demonstrated in this article has notable limitations—and possible improvements. First, although this behavior enables simple drag-and-drop in a single container, it does not allow for more robust application logic during the various stages of a drag-and-drop operation. Methods available in WPF, such as DragEnter, DragLeave, and Drop are not available, but you could add them through a custom attached event implementation.

See also  Custom Java Web Development - The Heartbeat of Modern Web Development

The behavior also is not able to perform custom drag-and-drop logic after setting IsEnabled. If using Canvas.Top and Canvas.Left in a drag-and-drop implementation was meaningful to an application, you would have to write a separate attached behavior rather than using custom events. This again is due to Silverlight’s lack of attached events. Look for many of these features and more in the upcoming release of Silverlight 3. However, you can overcome all these limitations through a more complex implementation of the behavior (which is outside the scope of this article). The implementation outlined here is intended as a starting point to a larger implementation that is available through the new open source Silverlight library Quasar.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist