2012-05-31 2 views

Antwort

35

Meinst du, du möchtest nur alle Kindelemente entfernen?

canvas.Children.Clear(); 

sieht aus wie es sollte den Job machen.

EDIT: Wenn Sie nur die Image Elemente entfernen möchten, können Sie:

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

Dieses Kind-Elemente, obwohl alle Bilder sind direkt übernimmt - wenn Sie Image Elemente entfernen möchten unter andere Elemente wird es schwieriger.

6

Da die untergeordnete Auflistung eines Canvas eine UIElementCollection ist und viele andere Steuerelemente diesen Sammlungssytem verwenden, können wir allen Methoden eine remode-Methode mit einer Erweiterungsmethode hinzufügen.

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++; 
     } 
    } 
} 

Wenn diese Klasse vorhanden ist, können Sie einfach alle Bilder (oder jede andere Art von Objekt) mit der Linie entfernen.

testCanvas.Children.Remove<Image>();