B
B
BadCats2017-07-08 15:03:58
WPF
BadCats, 2017-07-08 15:03:58

Create Grid programmatically in wpf?

You need to create a Grid with a size of 12 * 3 - that is, 12 in length and 3 in height,
and assign a button to each cell
. Did this:

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            RowDefinitionCollection rd = MainGrid.RowDefinitions;
            ColumnDefinitionCollection cd = MainGrid.ColumnDefinitions;
            for (int i = 0; i < 3; i++)
            {
                rd.Add(new RowDefinition());
                for (int j = 0; j < 12; j++)
                {
                  cd.Add(new ColumnDefinition());
                }
                
                Button b = new Button();
                b.Name = "Button"+i;
              
            }

In Window_Loaded, in cycles I created rows and columns and buttons - I gave the name of the created button.
But when the application started, not a single button appeared at all - this is firstly and secondly, how can I now assign the corresponding cell to each button through the code in the cycle?
MainGrid - the name I gave to the Grid present on the form

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sanostee, 2017-07-08
@BadCats

RowDefinitionCollection rd = MainGrid.RowDefinitions;
ColumnDefinitionCollection cd = MainGrid.ColumnDefinitions;
for (int i = 0; i < 3; i++)
{
    rd.Add(new RowDefinition());

    for (int j = 0; j < 12; j++)
    {
      cd.Add(new ColumnDefinition());
      Button b = new Button();
      b.Name = "Button"+i;
      MainGrid.Children.Add(b);
      Grid.SetColumn(b, j);
      Grid.SetRow(b, i);
    } 
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question