Reputation: 293
I want to add text to my canvas in WPF. The code runs until I want to add the TextBlock to the canvas as a child, giving me this:
"Specified element is already the logical child of another element. Disconnect it first."
Here is the relevant code:
private void txtbItemName_TextChanged(object sender, TextChangedEventArgs e)
{
TextBlock txtItemName = new TextBlock();
txtItemName.Text = txtbItemName.Text;
txtItemName.Margin = new Thickness(10, 10, 0, 0);
cnvImage.Children.Remove(txtItemName);
cnvImage.Children.Add(txtbItemName); //The error screen showed up when running this line
}
Upvotes: 0
Views: 506
Reputation: 371
It seems that your txtbItemName is already a child of an element in your XAML i suppose (can't see your XAML). because you have already created this element in your xaml it won't let you add it to the canvas.
Upvotes: 2
Reputation: 293
I found it: I indeed tried to place an object that was already present. I accidentally placed an existing textBOX (txtb) instead of a textBLOCK (txt). Thanks for the help though!
Upvotes: -2
Reputation: 825
You have an error. You are trying to remove the new item and add existing one.
Here is a right code for you:
TextBlock txtItemName = new TextBlock();
txtItemName.Text = txtbItemName.Text;
txtItemName.Margin = new Thickness(10, 10, 0, 0);
cnvImage.Children.Remove(txtbItemName);
cnvImage.Children.Add(txtItemName);
Upvotes: 3