L
L
lucky_e32015-06-18 10:05:24
WPF
lucky_e3, 2015-06-18 10:05:24

How to remove specific Image from Canvas?

It is required to go through all the Image and remove the Image that satisfies the condition.
I am using this code:

foreach (Image img in CnMapField.Children)
            {
                        if (img.Margin.Left == x)
                            CnMapField.Children.Remove(img);
            }

Gives an error message:
e374e11ef1274946a37ab20b6a7b9be9.PNG

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
Boris the Animal, 2015-06-19
@lucky_e3

Well, for example:

private void DoWork()
{
    Canvas CnMapField = new Canvas();

    Image[] images = CopyFrom<Image>(CnMapField.Children);
    foreach (Image img in images)
    {
        if (img.Margin.Left == x)
            CnMapField.Children.Remove(img);
    }
}

private T[] CopyFrom<T>(UIElementCollection collection) where T : UIElement
{
    var images = new List<T>(collection.Count);
    images.AddRange(collection.Cast<T>());
    return images.ToArray();
}

That is, you foreach (eat) run over a copy of the collection, and delete it from the original.
Although in this case, casting to Image is not necessary.

D
Daniil Basmanov, 2015-06-18
@BasmanovDaniil

You're modifying the collection you're iterating over - you can't do that. You can use the RemoveAll method:

CnMapField.Children.RemoveAll(img => img.Margin.Left == x);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question