2012-05-31 12 views
16

में जोड़े गए सभी चित्रों को हटाएं क्या सी # (डब्लूएफपी में) Canvas में जोड़े गए सभी छवियों (बच्चों) को हटाने (हटाने) का कोई संभावित तरीका है?कैनवास

उत्तर

35

क्या आपका मतलब है कि आप बस सभी बाल तत्वों को हटाना चाहते हैं?

canvas.Children.Clear(); 

ऐसा लगता है कि यह नौकरी करना चाहिए।

संपादित करें: यदि आप केवलImage तत्वों को निकालना चाहते हैं, तो आप उपयोग कर सकते हैं:

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

इसका मतलब यह है सभी छवियों प्रत्यक्ष बच्चे तत्वों हालांकि कर रहे हैं - आप के तहत Image तत्वों को निकालना चाहते हैं अन्य तत्व, यह trickier बन जाता है।

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>();