Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all images added to canvas

Is there a possible way to remove (delete) all images (children) added to a Canvas in C# (in WFP)?

like image 492
Ionică Bizău Avatar asked May 31 '12 14:05

Ionică Bizău


2 Answers

Do you mean you just want to remove all the child elements?

canvas.Children.Clear();

looks like it should do the job.

EDIT: If you only want to remove the Image elements, you can use:

var images = canvas.Children.OfType<Image>().ToList();
foreach (var image in images)
{
    canvas.Children.Remove(image);
}

This assumes all the images are direct child elements though - if you want to remove Image elements under other elements, it becomes trickier.

like image 144
Jon Skeet Avatar answered Oct 01 '22 06:10

Jon Skeet


Since the children collection of a Canvas is a UIElementCollection and there are plenty of other controls that use this type of collection, we could add remove method to all of them with an extension method.

public static class CanvasExtensions
{
    /// <summary>
    /// Removes all instances of a type of object from the children collection.
    /// </summary>
    /// <typeparam name="T">The type of object you want to remove.</typeparam>
    /// <param name="targetCollection">A reference to the canvas you want items removed from.</param>
    public static void Remove<T>(this UIElementCollection targetCollection)
    {
        // This will loop to the end of the children collection.
        int index = 0;

        // Loop over every element in the children collection.
        while (index < targetCollection.Count)
        {
            // Remove the item if it's of type T
            if (targetCollection[index] is T)
                targetCollection.RemoveAt(index);
            else
                index++;
        }
    }
}

When this class is present you can simply remove all images (or any other type of object) with the line.

testCanvas.Children.Remove<Image>();
like image 41
Andy Avatar answered Oct 01 '22 04:10

Andy