Andrew Foot
Andrew Foot

Reputation: 119

How to set children property in a canvas event handler?

I've got a canvas and inside it will be a shape. That canvas has a MouseLeftButtonDown event handler. I then went to move the shape in the canvas to a new location however nothing happens.

Here is how the shape is added:

public MainWindow()
    {
        InitializeComponent();
        Rectangle ShapeRect = new Rectangle() { Width=10,Height=10,Fill=Brushes.Blue};
        Canvas_1.Children.Add(ShapeRect);            
    }

Here is the event handler:

private void Canvas_1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Canvas c = Canvas_1;
        var firstchild = c.Children[0];
        var RectCopy = c.Children.OfType<Rectangle>().FirstOrDefault();              

        Canvas.SetTop(RectCopy, Canvas.GetTop(RectCopy) + 500);
        Canvas.SetLeft(RectCopy, Canvas.GetLeft(RectCopy) + 500);
    }

I've tested the code and it has no errors and all lines run but clearly have no effect. I think it's due to the fact that RectCopy isn't ShapeRect. Any different solution or answers is welcome. Thanks.

Upvotes: 0

Views: 228

Answers (1)

Troels Larsen
Troels Larsen

Reputation: 4631

Add the following lines at the bottom of your Initialize method:

Canvas.SetTop(ShapeRect, 0);
Canvas.SetLeft(ShapeRect, 0);

When you get to your handler, the values of Canvas.GetTop(...) is NaN.

Upvotes: 1

Related Questions