WEBINAR:
On-Demand
Building the Right Environment to Support AI, Machine Learning and Deep Learning
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.