I've got some custom controls which are dynamically added to a custom grid. These controls can span over several columns and rows(which are all the same size). I'd like to drag and drop between the rows and columns. I can drag the individual controls, but they can move anywhere without limit. Even off the grid. I'd like to do it so it can only be dragged inside the grid AND snaps to the column/row it's dragged to.
Is there any easy-ish way to do this?
Honestly, if I could get the current row/column that it's over, then all I'd need to do is set the column/row of it to them and that would probably do it and then just worry about keeping it inside the grid.
I'd say that the answer to this question very much depends on your experience using Drag and Drop functionality... for a beginner, I'd say that the answer to this was no, but for someone with some experience and some common sense, it might not be too bad.
To determine which
Grid
cell the user's mouse is over will not be straight forward. You can handle thePreviewDragOver
event and use theVisualTreeHelper.HitTest
method to check which control the mouse is currently over:The
GetParentOfType
method is a useful extension method that I created, but you can convert it to a normal method easily enough:Of course, once you have a
Control
in yourcontrolUnderMouse
variable, you'll still have some considerable work to do as you work your way through theUIElement
s until you get to theGrid
... you can of course make further use of theGetParentOfType
method to make your job easier.I figured out a nice and fun way!
I worked out the position on the grid that the the mouse is on on the MouseUp event and then the relative position of the mouse on the control since it spans several rows/columns.
I then take away the relative positions from the normal positions so that when you drop it, it always drops on the top left of the screen. When I move my controls, I use margins to move it, which screws up the position on the grid at the time, as shown below:
To tackle this, I simply reset the margin.
I hope this helps someone else since it was rather frustrating for me to find the answer and in the end I managed to get lots of little fragments of how to do things and eventually came up with my own solution.