Reputation: 2085
I'm trying to do something which is as simple as adding elements to a 6x7 grid through code behind. The grid is defined in xaml as following
<Grid x:Name="CalendarGrid" Grid.Row="1" Visibility="Collapsed">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
I have a function called InitializeCalendar which would populate the grid with buttons. Somehow I cant figure out how to specify row and column to which I want to add the button. How to I reference the row and column of CalendarGrid?
void InitializeCalendar()
{
for (int i = 0; i < 6; i++)
{
for (int j = 0; i < 7; j++)
{
butArray[i + 1, j + 1] = new Button();
//CalendarGrid. I cant find function to specify the row and button
}
}
}
I found that there is a property called ColumnProperty.
butArray[i + 1, j + 1].SetValue(Grid.ColumnProperty, 0);
But then there are so many Grids in my page. How do I reference the CalendarGrid? Any solutions?
Thanks,
Upvotes: 0
Views: 4599
Reputation: 19296
You can use Grid.SetRow
(msdn) and Grid.SetColumn
(msdn) methods:
void InitializeCalendar()
{
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 7; j++)
{
butArray[i, j] = new Button();
butArray[i, j].Content = (i).ToString() + (j).ToString();
CalendarGrid.Children.Add(butArray[i, j]);
Grid.SetRow(butArray[i, j], i);
Grid.SetColumn(butArray[i, j], j);
}
}
}
Upvotes: 2
Reputation: 6424
You have to add the button to the CalendarGrid. Try the following way:
CalendarGrid.Children.Add(butArray[i + 1, j + 1]);
butArray[i + 1, j + 1].SetValue(Grid.ColumnProperty, columnNumber);
butArray[i + 1, j + 1].SetValue(Grid.RowProperty, rowNumber);
Upvotes: 2