locked
Remove UserControls from Grid satisfying a condition RRS feed

  • Question

  • Hi,

    I have a Grid named "BoxGrid" in XAML, which has several UserControl (BoxControl) objects added to it as Children. Each BoxControl has some layout and TextBlocks. One TextBlock is unique to each control; it is named "id" (x:Name="id").

    What I want to do is to programmatically delete some of the BoxControls from BoxGrid. I have a list, deletelist, which contains the integer id of those BoxControls which I want to delete (see below).

    List<int> deletelist = new List<int>();
    
                foreach (BoxControl box in BoxGrid.Children)
                {
                    if (box.Selected)
                        deletelist.Add(Int16.Parse(box.id.Text));
                }

    The task would be: delete from BoxGrid.Children those BoxControls with an id = <id in BoxControl>.

    I would figure this could be done with LINQ or similar, but I don't have much experience with it at this time.

    Help would be appreciated. :)

    Monday, March 10, 2014 10:50 AM

Answers

  • I think I solved it myself. :)

    Instead of have a list of integers or string representing the id of the boxcontrols I wanted to delete, I made a list of the boxcontrol objects themselves to be deleted. Then I could use the PresentationFrameworkCollection<T>.Remove method:

    List<BoxControl> objectlist = new List<BoxControl>();
    
                foreach (BoxControl box in BoxGrid.Children)
                {
                    if (box.Selected)
                        objectlist.Add(box);
                }
                
                foreach (BoxControl box in objectlist)
                {
                    BoxGrid.Children.Remove(box);
                }
    The usercontrols are now successfully removed from the Grid.

    Monday, March 10, 2014 11:10 AM