删除添加到画布的所有图像

时间:2012-05-31 14:38:04

标签: c# .net wpf image wpf-controls

是否有可能删除(删除)添加到C#中的Canvas的所有图像(子项)(在WFP中)?

2 个答案:

答案 0 :(得分:35)

您的意思是您只想删除所有子元素吗?

canvas.Children.Clear();

看起来应该可以胜任。

编辑:如果想删除Image元素,您可以使用:

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

这假设所有图像都是直接子元素 - 如果要删除其他元素下的Image元素,则会变得更加棘手。

答案 1 :(得分:6)

由于Canvas的子集合是一个UIElementCollection,并且有很多其他控件使用这种类型的集合,我们可以使用扩展方法为所有这些集合添加remove方法。

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