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

18

有没有可能以C# (在WFP中)的方式删除添加到Canvas的所有图像(子项)?

有可能以C# (在WFP中)的方式删除添加到Canvas的所有图像(子项)。
2个回答

37

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

canvas.Children.Clear();

看起来应该能完成任务。

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

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

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


6

由于Canvas的children集合是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>();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接