有没有可能的方法来删除(删除)添加到Canvas
C#(在 WFP 中)中的所有图像(子项)?
问问题
17535 次
2 回答
37
你的意思是你只想删除所有的子元素?
canvas.Children.Clear();
看起来它应该完成这项工作。
编辑:如果您只想删除Image
元素,您可以使用:
var images = canvas.Children.OfType<Image>().ToList();
foreach (var image in images)
{
canvas.Children.Remove(image);
}
这假设所有图像都是直接子元素 - 如果您想删除Image
其他元素下的元素,它变得更加棘手。
于 2012-05-31T14:39:32.827 回答
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>();
于 2012-05-31T14:58:22.667 回答