现在我想在鼠标单击事件上在画布上绘制一个矩形。这是我的代码:
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);
}