Home > Net >  get Y-Position out of the Rectangle Hashcode
get Y-Position out of the Rectangle Hashcode

Time:10-20

everyone, I have a linechart on a Canvas. I placed a rectangle over each data point and added a MouseEnter event.

private void SetDataPointLabels(Point pt)
    {
        
        Rectangle rec = new Rectangle();
        rec.Stroke = Brushes.Red;
        rec.StrokeThickness = 1;
        rec.Width = 5;
        rec.Height = 5;
        rec.MouseEnter  = Rec_MouseEnter;
        Canvas.SetTop(rec, pt.Y - 2.5);
        Canvas.SetLeft(rec, pt.X - 2.5);
        ChartCanvas.Children.Add(rec);            
    }

I now need the y-position of the rectangle in the event method.

private void Rec_MouseEnter(object sender, MouseEventArgs e)
    {            
        Console.WriteLine(sender.GetHashCode());
    }

In the sender I found the Y position under VisualOffset.

Unfortunately, you can probably only get it via the hash code (sender.GetHashCode()) and I don't know how. Can anyone help me? Thank you Chris

CodePudding user response:

The sender argument holds a reference to the Rectangle instance and can therefore be cast to the Rectangle type:

private void Rec_MouseEnter(object sender, MouseEventArgs e)
{            
    var rec = (Rectangle)sender;
    var y = Canvas.GetTop(rec);
    Debug.WriteLine(y);
}

Or just cast to UIElement if you want to use the event handler also for other element types:

var y = Canvas.GetTop((UIElement)sender);
  • Related