Is there a possible way to remove (delete) all images (children) added to a Canvas
in C# (in WFP)?
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.
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With