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);
}
You are calling:
And then:
Which will add another new
Rectangle
into yourCanvas.Children
collection. If you want to remove the old one first, then call this first: