I have a drag/drop operation on a Canvas that is supposed to do something when an object gets dragged into and out of it. My problem is that the DragEnter/DragLeave events keeps firing as the mouse moves the object over it, not just on enter/exit. The faster the mouse is moving, the more frequently the events fire.
The Canvas DragOver Event moves the Canvas.Top/Left of the DraggedObject and I think that might be my problem, but I am not sure how I would fix this.
Here is the sequence of events:
DragEnterevent fires on the Canvas.DragEnterhandler moves the Panel so that it is now under the mouse. Since the mouse is no longer over the Canvas (it is over the Panel), theDragLeaveevent fires.The faster you move the mouse, the more events you will receive.
The essence of your problem is that drag-drop uses hit testing, and by moving your panel you are defeating the ability of hit testing to see “behind” your panel to know what container it is being dropped in.
The solution is to use your own code for drag and drop handling, which is really not difficult at all. WPF’s hit testing engine is powerful enough to do hit-testing behind the current object but drag-drop doesn’t make use of this functionality. You can use it directly however by using the
VisualTreeHelper.HitTestoverload that takes aHitTestFilterCallbackand aHitTestResultCallback. Just pass it a filter that ignores any hits within the panel being dragged.I’ve found that for scenarios like you describe, doing drag-drop by handling mouse events is actually easier than using the built in DoDragDrop because you don’t have to deal with the complexity (DataObject, DragDropEffects, QueryContinueDrag, etc). This additional complexity is very important for enabling scenarios of dragging between applications and processes, but does not help you for what you are doing.
Here’s the simple solution:
Enjoy.