现在我想在鼠标点击事件上在画布上绘制一个矩形。这是我的代码:
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);
}
答案 0 :(得分:3)
您正在致电:
rect = new System.Windows.Shapes.Rectangle(...);
然后:
canvas1.Children.Add(rect);
将另一个新Rectangle
添加到您的Canvas.Children
集合中。如果您想先删除旧的,请先调用它:
canvas1.Children.Remove(rect);