Есть ли способ удалить (удалить) все изображения (дети), добавленные в Canvas
в С# (в WFP)?
Удалить все изображения, добавленные в холст
Ответ 1
Вы хотите просто удалить все дочерние элементы?
canvas.Children.Clear();
похоже, что он должен выполнять эту работу.
EDIT: Если вы хотите удалить элементы Image
, вы можете использовать:
var images = canvas.Children.OfType<Image>().ToList();
foreach (var image in images)
{
canvas.Children.Remove(image);
}
Это предполагает, что все изображения являются прямыми дочерними элементами, хотя - если вы хотите удалить элементы Image
под другими элементами, становится сложнее.
Ответ 2
Поскольку дочерняя коллекция 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 of type T
if (targetCollection[index] is T)
targetCollection.RemoveAt(index);
else
index++;
}
}
}
Когда этот класс присутствует, вы можете просто удалить все изображения (или любые другие типы объектов) с помощью строки.
testCanvas.Children.Remove<Image>();