Dynamically Populate a UWP Grid using C#

This technique works for columns and rows, you just have to use the correct definition object, ColumnDefinition or RowDefinition.

Note the references to your specific grid instance (e.g. myGrid) and Grid methods (e.g. Grid.SetRow()).

myGrid.Children.Clear();
myGrid.ColumnDefinitions.Clear();

ColumnDefinition colDef;

for(int i = 0; i < myArray.Length; i++)
{
  colDef = new ColumnDefinition();
  myGrid.ColumnDefinitions.Add(colDef);
  colDef.MinWidth = 50;

  // Create a new instance of a TextBlock
  // or any other control; making a factory 
  // method(s) is usually wise.
  TextBlock txt = MyTextBlockFactoryMethod();
  myGrid.Children.Add(txt);
  Grid.SetRow(txt, 0);
  Grid.SetColumn(txt, i);
  txt.Text = myArray[i].ToString();
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s