UWP C#动态添加按钮并在StackPanel上进行组织

我知道有一些post询问有关动态添加按钮但我无法找到如何在stackpanel上组织它们。 我没有添加新按钮的问题,但有没有办法在列和行中组织它们?

   

请帮忙。 谢谢。

更新:我想根据点击按钮的次数添加按钮。 它添加到第4个rom然后移动到下一个/新列。 在此处输入图像描述

根据我的评论,也可以使用Grid 。 要实现所需的布局,您可以使用以下内容:

XAML:

               

我用一个Grid替换了你的StackPanel ,并添加了四行和第一列的定义。

CS:

首先我们需要添加一个计数器:

 public int buttonCounter = 1; 

然后我们需要更改Button_Click方法:

 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++; } 

在此方法中,将自动计算新按钮的位置,如果需要,会在网格中添加新列。

试试这个:

     

如果您需要在开头有一个按钮,则在初始化视图时,请执行以下操作:

  Button b = new Button(); ; b.Content = "Button"; b.Click += Button_Click; ButtonsUniformGrid.Children.Add(b); 

然后,每次单击它都会在网格中放置一个新按钮。 如果您对此有任何其他疑问,请告诉我:)


如果您没有在xaml中指定它,则评论Uwp不包括UniformGrid 。 如果你想使用它,只需包括:

 xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls" 

你的UniformGrid将是这样的: