有没有可能以C# (在WFP中)的方式删除添加到Canvas
的所有图像(子项)?
Canvas
的所有图像(子项)。有没有可能以C# (在WFP中)的方式删除添加到Canvas
的所有图像(子项)?
Canvas
的所有图像(子项)。你的意思是你只想删除所有子元素吗?
canvas.Children.Clear();
看起来应该能完成任务。
编辑:如果你只想删除Image
元素,可以使用:
var images = canvas.Children.OfType<Image>().ToList();
foreach (var image in images)
{
canvas.Children.Remove(image);
}
假设所有图像都是直接的子元素 - 如果您想删除其他元素下的Image
元素,则会变得更加棘手。
由于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>();