Im trying to add a Child to a StackPanel ("messageChain") which is inside a StackPanel ("newMessage") which is inside ANOTHER StackPanel ("Messages").
Im basically trying to make a chat with messages and profile pictures but i came up with these "message chains" because if i dont have those then every message will contain a profile picture which i dont want, i want a profile picture to only be next to the first message.
Ive read other questions about this but im still not sure if i understand... can i not add children to an existing StackPanel within an existing StackPanel within an existing StackPanel? Creating the first message works, but creating the second doesnt and gives an exception because thats where i try to add a child to the nested StackPanel.
If this isnt possible, what would be a better way to do what im trying to do?
Anyway here is the code, and under it the exception i get and a screenshot of what im trying to do, in case my explanation doesnt make sense
// New message chain
StackPanel messageChain = new StackPanel();
messageChain.Children.Add(messageTB);
// Create horizontal message StackPanel (PFP & MessageChain) for new message
StackPanel newMessage = new StackPanel();
newMessage.Name = "Local";
newMessage.Orientation = Orientation.Horizontal;
newMessage.Margin = new Thickness(0, 0, 10, 5);
newMessage.HorizontalAlignment = HorizontalAlignment.Left;
if (Messages.Children.Count <= 0)
{
newMessage.Children.Add(pfpGrid);
newMessage.Children.Add(messageChain);
Messages.Children.Add(newMessage);
}
else
{
if (Messages.Children[Messages.Children.Count - 1] is StackPanel msg)
{
if (msg.Name == "Local")
{
if (msg.Children[1] is StackPanel msgChain) // this adds the new message textblock to the previously created StackPanel "messageChain" which is inside the also previously created StackPanel "newMessage"
{
msgChain.Children.Add(messageTB); // EXCEPTION: CANT add new TextBlock to already existing StackPanel
}
}
else
{
newMessage.Children.Add(pfpGrid);
newMessage.Children.Add(messageTB); //message wont wrap here
Messages.Children.Add(newMessage);
}
}
}
This is the exception i get (i commented where i get it in the code):
System.InvalidOperationException: Specified element is already the logical child of another element. Disconnect it first. at System.Windows.FrameworkElement.ChangeLogicalParent(DependencyObject newParent) at System.Windows.FrameworkElement.AddLogicalChild(Object child) at System.Windows.Controls.UIElementCollection.AddInternal(UIElement element) at System.Windows.Controls.UIElementCollection.Add(UIElement element) at Soxkets.ServerPage.Chatbox_KeyDown(Object sender, KeyEventArgs e) in C:\Users\demented\Desktop\C#Programs\Soxkets\ServerPage.xaml.cs:line 333
Here is a screenshot explaining what im trying to do, if that helps: