Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Robust, Reusable Drag-and-Drop Behavior in Silverlight : Page 2

By manipulating an element's RenderTransform with attached behaviors, you can greatly increase the overall robustness and reusability of any drag-and-drop implementation in Silverlight.


advertisement

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.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap