Parni
Parni

Reputation: 141

Detect which rectangle has been clicked in Canvas WPF

I have a WPF canvas filled programmatically with a series of rectangles (lets say 100, but the number vary each time). My problem is that I need to detect which rectangle is clicked by the user. I thought to assign to each rectangle a different unique Name and and the same event "MouseLeftButtonDown" for every rectangle, but then I don't know how can I get the Name of the object which has been clicked. Can anyone help me?There is also the possibility to check in which point of the screen the mouse clicked, get the coordinates and then calculate which rectangle is around that point, but it seems too complicate for such a stupid problem. Thank you in advance!

Upvotes: 4

Views: 3567

Answers (2)

Dragos Stoica
Dragos Stoica

Reputation: 1935

You can get your rectangle by name like this if all rectangles are bounded to OnMouseDownEvent to Rectangle_OnMouseDown function :

private void Rectangle_OnMouseDown(object sender, MouseButtonEventArgs e)
    {
        var mouseWasDownOn = e.Source as FrameworkElement;
        if (mouseWasDownOn != null)
        {
            string elementName = mouseWasDownOn.Name;
            var myRectangle = (Rectangle)this.FindName(elementName);
        }
    }

Upvotes: 2

MRebai
MRebai

Reputation: 5474

Try to use canavas events :

private void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
      if (e.OriginalSource is Rectangle)
      {
        Rectangle ClickedRectangle = (Rectangle)e.OriginalSource;

        // Your work here I give y some actions ...
        ClickedRectangle.Opacity = 0.5;
        if (e.ClickCount == 2)
        {
          canvas.Children.Remove(ClickedRectangle);
        }
        else
        {
          isPressed = true;
          startPosition = e.GetPosition(canvas);
          ClickedRectangle.CaptureMouse();
        }
      }
    }

Upvotes: 2

Related Questions