Title: Move and resize multiple rectangles in WPF and C#
The example Let the user move and resize a rectangle in WPF and C# shows how to let the user move and resize a single rectangle in a WPF program. This example extends that one to let you move and resize multiple rectangles.
See the earlier example for the basic idea.
This example makes a relatively simple modification. Instead of using a single rectangle, it uses a list containing multiple rectangles. The following code declares and initializes the list.
// The Rectangles that the user can move and resize.
private List<Rectangle> Rectangles;
// Make a list of the Rectangles that the user can move.
private void Window_Loaded(object sender, RoutedEventArgs e)
Rectangles = new List<Rectangle>();
foreach (UIElement child in canvas1.Children)
if (child is Rectangle)
Rectangles.Add(child as Rectangle);
// Reverse the list so the Rectangles on top come first.
The program's window holds a Canvas control that contains the Rectangle controls. It also contains a Border to show that you don't need to let the user move every control.
The window's Loaded event handler creates the list and then loops through the Canvas control's children. It adds the Rectangle controls that it finds to the Rectangles list.
After it has examined all of the children, the method reverses the order of the Rectangle controls so they appear in the list in top-to-bottom order.
The following method determines what if anything is at a particular point.
// The part of the rectangle under the mouse.
private HitType MouseHitType = HitType.None;
// The Rectangle that was hit.
private Rectangle HitRectangle = null;
// If the point is over any Rectangle,
// return the Rectangle and the hit type.
private void FindHit(Point point)
HitRectangle = null;
MouseHitType = HitType.None;
foreach (Rectangle rect in Rectangles)
MouseHitType = SetHitType(rect, point);
if (MouseHitType != HitType.None)
HitRectangle = rect;
// We didn't find a hit.
This method loops through the Rectangles list and calls the SetHitType method for each of the Rectangle controls in the list. If SetHitType finds that the target point is over a Rectangle, then FindHit saves the hit type and the Rectangle that was hit in form-level variables and exits.
The rest of the program is similar to the earlier example except it uses the Rectangle stored in the variable HitRectangle instead of the single Rectangle used by the earlier example.
Download the example to experiment with it and to see additional details.