You need to keep references to the
Grid
s until you want to delete them. (The
Grid
s keep the references to the
Button
s.)
For your example, create a private field in the window class:
private List<Grid> DynamicGrids = new List<Grid>();
Then add:
DynamicGrids.Add(gg);
to the
for
loop that creates the
Grid
s and
Button
s.
Then when you want to remove them:
foreach (Grid g in DynamicGrids)
{
ThumGrid.Children.Remove(g);
}
This assumes that
ThumGrid
contains other elements that you don't want to remove, otherwise it is simply:
ThumGrid.Children.Clear();
Be careful not to Remove elements from
ThumGrid.Children
while iterating over that collection with an
IEnumerator
(e.g.,
foreach
) or else you will throw an exception:
System.InvalidOperationException
.