Friday, December 24, 2010

Silverlight–Adding columns and rows dynamically

Here is some code that shows you how to add rows and columns dynamically in Silverlight/Windows Phone 7.

The code depends on a Grid called ContentPanel defined in the XAML (found by default on a WP7 page).

ContentPanel.ColumnDefinitions.Clear();
ContentPanel.RowDefinitions.Clear();
int numColumnsToAdd = 4;
int numRowsToAdd = 4;
for (int column = 0; column < numColumnsToAdd; column++)
{
ColumnDefinition cd = new ColumnDefinition();
cd.Width = new GridLength(200);
ContentPanel.ColumnDefinitions.Add(cd);
}

for (int row = 0; row < numRowsToAdd; row++)
{
RowDefinition rd = new RowDefinition();
rd.Height = new GridLength(200);
ContentPanel.RowDefinitions.Add(rd);
}
//add an image into each
for (int row = 0; row < numRowsToAdd; row++)
{
for(int col = 0; col < numColumnsToAdd; col++)
{
TextBlock txt = new TextBlock();
txt.Text = "Hello";
ContentPanel.Children.Add(txt);
Grid.SetColumn(txt, col);
Grid.SetRow(txt, row);
}
}

And here is the result:

image

1 comment:

itmgmg said...

Thanks you, I m finding this.
I m trying to create calendar control.