Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I'm working on my first project in UWP. I now try drag and drop items but can't get this to work. As UWP has new ways of performing drag and drop it's hard to find some code that does what I am looking for.

I have small canvases inside a larger canvas (they are going to become chess pieces on a chessboard). So I simply want to be able to drag the canvases on top of other small canvases (that is, moving a piece on top of another piece).

I need to do this in codebehind, in the method where I create the canvases (pieces). What I am trying is this:


C#
cnv.CanDrag = true;
cnv.AllowDrop = true;
cnv.DragEnter += new DragEventHandler(cnv_DragEnter);
cnv.Drop += new DragEventHandler(cnv_DragDrop);
cnv.DragStarting += new DragEventHandler(cnv_DragStarting);
cnv.DropCompleted += new DragCompletedEventHandler(cnv_DragCompleted);


(My DragEnter code works, but the eventhandler for DragStarting won't work the way it's written above.)

I need to be able to check whether the player can move the canvas (piece) in question, and what happens when the canvas (piece) gets dropped - is the move allowed and should it remove another piece? I already have the logic from an old application - I just need the correct code for my events.

All the examples I have found so far work on listviews and I have no idea what to write really.

Thanks!

Petter
Posted
Updated 6-Jan-16 22:26pm
v2

1 solution

I don't know UWP but I will try to help.

While you are using drag and drop inside one control type you should still differentiate between source and destination. DragEventHandler is for drag events on the destination only.

Source (UIElement events)

Destination (DragEventHandler[^])

  • DragEnter (initialisation)
  • DragOver (check if dropping at position possible)
  • Drop (when dropping possible)
  • DragLeave (optional cleanup when dropping not possible)


All checking should be implemented on the destination side (can the piece be dropped at the current position, is the move allowed). To check if the move is allowed use the OriginalSource member of the passed DragEventArgs.

Then it would be only necessary to handle DragStarting to check if there is something to drag. But that can be omitted when disabling dragging for fields that are empty (initialise upon start, disable after successful move, and enable upon drop).
 
Share this answer
 
Comments
petter2012 7-Jan-16 20:24pm    
Hi,

Thanks for some very useful information! This will make the task easier.

Best wishes for the new year.

Petter

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900