Draw rectangle and update it on every mouse click

2019-08-16 05:41发布

问题:

Now I want to draw a rectangle on canvas on mouse click Event. Here is my code:

    protected void imageIR_MouseClick(object sender, System.Windows.Input.MouseEventArgs e)
    {
    ...
        System.Windows.Point startPoint = e.GetPosition(canvas1);
        rect = new System.Windows.Shapes.Rectangle
        {
            Stroke = System.Windows.Media.Brushes.LightBlue,
            StrokeThickness = 10
        };
        Canvas.SetLeft(rect, startPoint.X);
        Canvas.SetTop(rect, startPoint.Y);
        canvas1.Children.Add(rect);
    }

    private void Canvas_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
    {
        rect = null;
    }

It works fine everytime I clicked the mouse, but why is the old rectangle still on the canvas when I redraw the new one? What I did wrong?

EDIT Now it's correct, I don't Need Canvas_MouseMove anymore and instead:

    protected void imageIR_MouseClick(object sender, System.Windows.Input.MouseEventArgs e)
    {
    ...
        canvas1.Children.Remove(rect);
        System.Windows.Point startPoint = e.GetPosition(canvas1);
        rect = new System.Windows.Shapes.Rectangle
        {
            Stroke = System.Windows.Media.Brushes.LightBlue,
            StrokeThickness = 10
        };
        Canvas.SetLeft(rect, startPoint.X);
        Canvas.SetTop(rect, startPoint.Y);
        canvas1.Children.Add(rect);
    }

回答1:

You are calling:

rect = new System.Windows.Shapes.Rectangle(...);

And then:

canvas1.Children.Add(rect);

Which will add another new Rectangle into your Canvas.Children collection. If you want to remove the old one first, then call this first:

canvas1.Children.Remove(rect);