views:

61

answers:

2

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"?

+1  A: 
        Grid parentGrid = VisualTreeHelper.GetParent(image) as Grid;

        if (parentGrid != null)
            parentGrid.Children.Remove(image);
Scott J
+2  A: 

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.

AnthonyWJones
thanks for suggesting this, what I do now is I think what you were suggesting: put the BitmapImages themselves directly in the dictionary, then let Images assign their ImageSource to any bitmap image it wants as many times as it wants, works fine and I don't have the above problem of trying to unattach elements from the visual tree
Edward Tanguay