I'm coding up a new project in C#/XAML for Windows 8 Metro. I'm trying to dynamically add cells to a grid. I want 3 columns, not just one, and I thought Grid would do the trick. The code I'm using is below. The problem is that each new Image added to the Grid first appears in one place and then moves to another -- or something; there's a lot of flickering. My content is dynamic (determined at runtime) so I can't code up the structure in XAML. The only thing I have in the XAML is the grid with definitions for three columns and one row.
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
StorageFolderQueryResult queryResult = picturesFolder.CreateFolderQuery();
IReadOnlyList<IStorageFolder> folderList = await queryResult.GetFoldersAsync();
int row = 0, col = 0;
foreach (IStorageFolder folder in folderList)
{
IReadOnlyList<IStorageFile> fileList = await folder.GetFilesAsync();
foreach (IStorageFile file in fileList)
{
Image image = new Image();
image.Source = await LoadImageFromFileAsync(file);
image.Width = 150;
image.Height = 150;
Grid.SetColumn(image, col);
Grid.SetRow(image, row);
++col;
if (col == 3)
{
col = 0;
++row;
RowDefinition rd = new RowDefinition();
GridLength gl = new GridLength() { Value = 150 };
rd.Height = gl;
grid.RowDefinitions.Add(rd);
}
grid.Children.Add(image);
}
}
So: how do I get rid of the flickering? Is there a way to set up an item template in the XAML to create three columns of items?