Edward Tanguay
Edward Tanguay

Reputation: 193352

How can I unattach an element from another element in the XAML tree?

In my Silverlight application, I load all the images I need at application start and store them in a dictionary.

Then as I need them I pick them out of the dictionary and attach them in XAML trees etc.

However, I have the problem that if I attach an Image object to a Grid, then want to use that image again, it tells me:

The image element is already a child of another element.

How can I run through my dictionary and "detach all images from parent XAML elements"?

Upvotes: 1

Views: 565

Answers (2)

AnthonyWJones
AnthonyWJones

Reputation: 189495

Instead of holding a dictionary of Image controls hold a dictionary of ImageSource instead. A single instance of an ImageSource can be assigned to multiple to Image controls.

However I suspect that creating an ImageSource on its own will not download the actual file until there is a demand. If that is the case your initialiser would still need to create a list of images that use these images sources and wait for all to indicate they have loaded. Then you could keep a dictionary of ImageSource and discard the list of actual Image controls.

Upvotes: 2

Scott J
Scott J

Reputation: 1331

        Grid parentGrid = VisualTreeHelper.GetParent(image) as Grid;

        if (parentGrid != null)
            parentGrid.Children.Remove(image);

Upvotes: 1

Related Questions