Reputation: 798
Is it possible to know the number of cells in a Grid? Could I access them in some way to append a child to each of them?
For example, if I have a 2 rows x 3 columns Grid:
<Grid Name="myGrid">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
</Grid>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
</Grid>
</Grid>
I have tried something like:
foreach (RowDefinition row in this.myGrid.RowDefinitions)
{
foreach(ColumnDefinition col in row)
{
// This doesn't work.
// There is no property ColumnDefinitions in row.
}
}
I can't figure out how to achive this (if possible).
Upvotes: 0
Views: 296
Reputation: 35680
RowDefinitions and ColumnDefinitions belong to Grid and they are independent from each other.
fix xaml definition to make a 2x3 Grid (instead of current 2x1, 1x3, 1x3 Grids)
<Grid Name="myGrid">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
</Grid>
Grid cells are not represented by any control. They are just rectangular areas in Grid, determined during arrange. Use Grid.RowProperty
and Grid.ColumnProperty
attached DP to position child elements in Grid:
for(int r = 0; r < myGrid.RowDefinitions.Count; r++)
{
for(int c = 0; c < myGrid.ColumnDefinitions.Count; c++)
{
var B = new Border { Margin = new Thickness(5), Background = Brushes.Green };
B.SetValue(Grid.RowProperty, r);
B.SetValue(Grid.ColumnProperty, c);
myGrid.Children.Add(B);
}
}
if all cells are of equal size, you can use UniformGrid:
<UniformGrid Name="myGrid" Rows="2" Columns="3"/>
for(int r = 0; r < myGrid.Rows; r++)
{
for(int c = 0; c < myGrid.Columns; c++)
{
var B = new Border { Margin = new Thickness(5), Background = Brushes.Green };
myGrid.Children.Add(B);
}
}
Upvotes: 1