I need to develop a structure similar to Windows 8 Start screen. I have a method which I call to populate my RecordTile
. Method is like,
public static void fnShowTiles(List<RecordTile> objList, Grid objGrid) // objGrid is root Grid which holds this structure
{
try
{
// copy the list into local variable
List<RecordTile> objListOfTiles = objList.ToList<RecordTile>();
int nColumnsCount = -1;
objGrid.Children.Clear();
objGrid.ColumnDefinitions.Clear();
StackPanel objPanel = new StackPanel();
int nOriginalListCount = objListOfTiles.Count;
int nRowsToRender = 4;
while (objListOfTiles.Count > 0)
{
// add new column to the grid
objGrid.ColumnDefinitions.Add(new ColumnDefinition());
nColumnsCount += 1;
// add new stackpanel to newly added column
objPanel = new StackPanel();
objGrid.Children.Add(objPanel);
Grid.SetColumn(objPanel, nColumnsCount);
// add elements to stackpanel
int i = 0;
while (i < nRowsToRender)
{
if (objListOfTiles.Count > 0)
{
// add first element and remove it from list, so that next element will be first
RecordTile tile = objListOfTiles.First();
objPanel.Children.Add(tile); // exception occurs here
objListOfTiles.Remove(tile);
i++;
}
else
{
// if while adding elements, list finishes, then break the loop
break;
}
}
}
}
This is working fine for the first load. I have a SearchBox
on the same page where these tiles are getting loaded. When I filter the Tiles (based on search string) and pass new list of tiles to the function, it throws exception.
I went through many posts. They suggested to remove element from its parent. I'm clearing the children of grid every time. What must be going wrong?
As @Rawling suggested, clearing the Tiles from StackPanel
before objGrid.Children.Clear();
was the solution. Added following code before that statement and it worked like a charm.
foreach (StackPanel panel in objGrid.Children)
{
panel.Children.Clear();
}