Click here to Skip to main content
15,741,947 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am creating a custom file picker. For that I require one Image object to be used by multiple folder which I have displayed as a StackPanel.
Image image = new Image();
image.Source = new BitmapImage(new Uri("I:/image.jpg"));

foreach(string s in Directory.GetDirectories("I:/"))
 StackPanel sp = new StackPanel();
sp.Children.Add(new TextBlock{Text = s,});

What I have tried:

This throws an InvalidOperationException since i cannot add single instance of an Image to multiple StackPanel.
Any help ?
Updated 29-May-16 11:50am

The rest of the error message is the important bit
Additional information: Specified element is already the logical child of another element. Disconnect it first.

You need to create the image within the foreach loop

You also need to put that stack panel into the visual part of your app (as a child of whichever container you are using in your XAML), otherwise you will never see the images
Share this answer
I have no idea what you are trying to achieve and why, what the final layout is supposed to look and why would you possibly need so many stack panels.

But at least one bug is obvious: all the instances of your stack panels created inside the loop are simply get lost. On each iteration, you create a new instance, and previously created instance becomes unreachable. After the loop, all instances of stack panels and text blocks created inside the loop become unreachable. Eventually, all these instances will be discarded by the Garbage Collector.

To use those UI elements, you would need to add them as children of some parent UI element.

Also, it looks like you are trying to add the same image into the logical tree of the same UI.

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900