0

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

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

1 回答 1

3

您正在调用:

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

接着:

canvas1.Children.Add(rect);

这将为您的收藏添加另一个新的。如果您想先删除旧的,请先调用它:RectangleCanvas.Children

canvas1.Children.Remove(rect);
于 2013-10-08T11:27:36.647 回答