开发者

How can I drag and drop a tile(image) into a specified place? WPF

开发者 https://www.devze.com 2023-03-13 21:21 出处:网络
I am creating a Map Editor for my game using WPF Forms. I have one problem though. How can I drag and drop a tile(image) into a specified place?

I am creating a Map Editor for my game using WPF Forms. I have one problem though. How can I drag and drop a tile(image) into a specified place?

I'll try to detail my need. Take for instance this image:

How can I drag and drop a tile(image) into a specified place? WPF

So what I want is that every tile - will be selected by the user and dragged to the grid area - is "attracted" to a cell. Is that clear? That way the user would see every tile in its place.

Does anyone know how to implement that?

Than开发者_开发问答ks.


I am not entirely sure if you are asking for "How to implement Drag&Drop?" or "How to prevent the user from dropping anywhere but within a specified location?", so I try to give some clues about both.

How to implement Drag&Drop?

To get basic drag&drop funcionality you would do something like this:

  • Set the AllowDrop property of your desired drag target to true.

  • Hook up for OnMouseMove and MouseLeftButtonDown to be able to detect the start of a D&D operation. (this events are in System.Windows.UIElement)

  • Hook up for OnPreviewDragEnter, OnPreviewDragLeave, OnPreviewDragOver, OnPreviewDrop (this events are in System.Windows.DragDrop)

  • Then you listen for OnMouseMove and MouseLeftButtonDown until the user initializes a drag operation (i.e. moved either SystemParameters.MinimumHorizontalDragDistance or SystemParameters.MinimumVerticalDragDistance wide while left mouse button was pressed)

  • At this point you will have to initialize a D&D operation with DragDrop.DoDragDrop

  • After the initialization you would listen for all the drag events listed above, but to get the basic functionality it is enough to listen for the OnPreviewDrop.

How to prevent the user from dropping anywhere but within a specified location?

After you have implemented the D&D functionality it is pretty straightforward to achieve this. Just check if the sender of OnPreviewDrop is the currently active drop target and ignore the drop event if it's not.

More

To find more detailed informations you should visit this Drag and Drop Overview. Since it is a game you would probably like to display the dragged content while dragging, you can achieve this with adorners. The provided example does not cover enough to get the preview of a dragged image displayed but google lists many good examples on the topic.

0

精彩评论

暂无评论...
验证码 换一张
取 消