Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 351
Parni Avatar asked Nov 05 '25 02:11

Parni


2 Answers

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);
        }
    }
like image 65
Dragos Stoica Avatar answered Nov 09 '25 10:11

Dragos Stoica


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();
        }
      }
    }
like image 36
Moez Rebai Avatar answered Nov 09 '25 08:11

Moez Rebai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!