I am developing a WPF in C# and I want to draw a specific line multiple times, without losing its previous trails. I have 10 buttons
inside my Grid
and its time I press one I want a line to be drawn. For the line, I use the var redLine
and each time I press a button, it receives a specific pair of coordinates.
I use this code to draw the line:
public partial class MainWindow : Window {
private Line redLine = new Line();
SolidColorBrush redBrush = new SolidColorBrush(Colors.Red);
public MainWindow()
{
redLine.StrokeThickness = 4;
redLine.Stroke = redBrush;
}
private void button1_Click(object sender, RoutedEventArgs e) {
redLine.X1 = 237;
redLine.Y1 = 382;
redLine.X2 = 288;
redLine.Y2 = 409;
//draw the line
MainGrid.Children.Add(redLine);
}
private void button2_Click(object sender, RoutedEventArgs e) {
redLine.X1 = 130;
redLine.Y1 = 323;
redLine.X2 = 238;
redLine.Y2 = 690;
//draw the line
MainGrid.Children.Add(redLine);
}
}
But every time I press button1
and then button2
I get this error (it also happens for the rest of the buttons):
ERROR Specified Visual is already a child of another Visual or the root of a CompositionTarget.
I do want to keep both lines and NOT to remove the first one in order to draw the second. Any ideas on how to solve it?
NOTE I do not want to declare each line (there are about 11 lines in the whole program) inside each buttonX_Click method.