UWP C# Add Button Dynamically and Organizing On StackPanel

前端 未结 2 908
天命终不由人
天命终不由人 2020-12-22 10:47

I understand there are a few post asking about adding buttons dynamically but I could not find out how to organize them on the stackpanel. I have no issue addi

2条回答
  •  伪装坚强ぢ
    2020-12-22 10:52

    From the comments i took, that it is possbile to use a Grid too. To achieve the desired layout you could use the following:

    XAML:

    
            
                
                    
                    
                    
                    
                
                
                    
                
                
            
        
    

    I replaced your StackPanel with a Grid and added definitions for the four rows and the first column.

    CS:

    First we need to add a counter:

    public int buttonCounter = 1;
    

    Then we need to change the Button_Click method:

    private void Button_Click(object sender, RoutedEventArgs e)
            {
    
                //Create the button
                Button b = new Button();
                b.Height = 30;
                b.Width = 100;
                b.VerticalAlignment = VerticalAlignment.Top;
                b.HorizontalAlignment = HorizontalAlignment.Left;
                b.Margin = new Thickness(20, 20, 0, 0);
                b.Content = "Button " + buttonCounter;
                b.Click += Button_Click;
    
                //Calculate the place of the button
                int column = (int)(buttonCounter / 4);
                int row = buttonCounter % 4;
    
                //Check if you need to add a columns
                if(row == 0)
                {
                    ColumnDefinition col = new ColumnDefinition();
                    col.Width = new GridLength(column, GridUnitType.Auto);
                    myGrid.ColumnDefinitions.Add(col);
                }
    
                //Add the button
                myGrid.Children.Add(b);
                Grid.SetColumn(b, column);
                Grid.SetRow(b, row);
                buttonCounter++;
            }
    

    Inside this method, the position of the new button is automatically calculated and if needed, a new column is added to the grid.

提交回复
热议问题