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.

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.

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.

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.

devx-admin

devx-admin

Share the Post:
USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted