Format a grid to display multiple labels containing data accross rows in the grid.
Continuing from the previous lesson where we added a label to a grid, in this lesson we will initialise our grid using a loop, building a row for every item of the list and populating the row with a label.
To start us off we are creating a blank python file to work from but there's nothing preventing you from editing the existing one as we go. Right clicking on the project in your solution explorer > Add > New Item...
Select the Empty Python File and name your new file, copy and paste the code from the previous example into this file line for line.
from System.Windows.Controls import Label, ColumnDefinition, RowDefinition
This time around we will need to import some controls to dynamically build rows for the Grid.
Now we can add the code to create a label, set the content of the label and add the label as a child of the grid.
myList = ['fred','John','Bill','Ste','Chris','Susan','Satya'] i = 0 for guest in myList: self.myGrid.RowDefinitions.Add(RowDefinition()) #creates a new row inside our grid (self.myGrid) self.makeLabel(guest, i) #calling the makeLabel funtion passing a reference to the list item and row index. i=i+1 #increment the row index so the next label is added to the line below def makeLabel(self, guest, i): myLabel = Label() #creates a new label in memory myLabel.Content = guest #myLabel is locally scoped so setting the content only applied to this iteration of the label self.myGrid.SetRow(myLabel, i) #sets the row for the new label self.myGrid.Children.Add(myLabel) #add the label as a child of the grid
That's it for this lesson, we've created a label for every item in our list, populated the label and added each label to our grid. In the next lesson we'll experiment with columns.