绘制矩形并在每次单击鼠标时更新它

时间:2013-10-08 11:20:11

标签: c# wpf canvas mouseclick-event drawrectangle

现在我想在鼠标点击事件上在画布上绘制一个矩形。这是我的代码:

    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;
    }

每次点击鼠标都可以正常工作,但是当我重新绘制新鼠标时,为什么旧​​的矩形仍然在画布上?我做错了什么?

编辑现在它是正确的,我不再需要Canvas_MouseMove而是:

    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 个答案:

答案 0 :(得分:3)

您正在致电:

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

然后:

canvas1.Children.Add(rect);

另一个Rectangle添加到您的Canvas.Children集合中。如果您想先删除旧的,请先调用它:

canvas1.Children.Remove(rect);