How to remove items from canvas

BitSmithy 1,751 Reputation points
2022-06-20T13:01:31.23+00:00

Hello,

I have a Canvas. This Canvas has obout 900+ UIElements as children.
Now I try to remove these uiElements from the Canvas.

foreach (var uie in cnvBattleArea.Children)
{
cnvBattleArea.Children.Remove(uie);
{

There is removed about half of them, rest of them stays in the Canavas.

If I use Canavas.Children.Clear() all works fine, and my Canvas stays empty.

How to remove items from canvas.children using Remove function.

Note: I must use remove, not clear, because sometime I dont remove all items but part of them.

Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Viorel 112.1K Reputation points
    2022-06-20T16:07:07.717+00:00

    Try something like this:

    var list = new List<UIElement>( );  
      
    foreach( var uie in cnvBattleArea.Children )  
    {  
        // if this element must be removed, then add it to list:  
        list.Add( uie );  
    }  
      
    foreach( var uie in list ) cnvBattleArea.Children.Remove( uie );  
    
    3 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful