简体   繁体   中英

Drawing squares in WPF

I want to achieve the following with a WPF application (in a certain area/defined area):

  • When clicking and holding on the app, you can draw a square
  • You can do this as many times, but not overlap any squares
  • You can drag squares around the application

What do I need to achieve this, I assume a bunch of onclick/onmove's. Is there an easier way, such as using canvas? Any insight would be great.

You will have to use a canvas if you want the squares to appear where the user clicks and drags.

The mouse down event would define one corner and the mouse up the second. You'd have to constrain the movement of the cursor so that the x and y dimensions of the rectangle were the same.

On each mouse move event you'd have to check if the cursor were over one of the existing squares and prevent the square growing any further.

For the dragging of existing squares modify the mouse down event to check what's under the cursor. If it's the canvas start the square drawing mode, if it's a rectangle (square) then start the dragging mode. Again you'd need to use the mouse move event to check that the square doesn't intersect with any existing squares.

There's a code project article describing how to drag elements inside a Canvas: Dragging Elements in a Canvas

Speaking of ChrisF's mentioning of using a Canvas, I would suggest you use DragCanvas (found in the article)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM