2012-05-31 8 views

答えて

35

すべての子要素を削除したいだけですか?

canvas.Children.Clear(); 

は仕事をする必要があります。

EDIT:あなたはだけImageの要素を削除したい場合は、使用することができます。

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

これは、すべての画像が直接子要素ががあると仮定し - あなたは下Imageの要素を削除する場合他の要素、それはより厄介になります。

6

キャンバスの子コレクションはUIElementCollectionであり、このタイプのコレクションを使用する他のコントロールがたくさんあるので、それらをすべて拡張メソッドで追加することができます。

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

このクラスが存在する場合は、そのラインですべての画像(または他のタイプのオブジェクト)を削除することができます。

testCanvas.Children.Remove<Image>(); 
関連する問題