UWP C# 动态添加按钮并在 StackPanel 上组织 [英] UWP C# Add Button Dynamically and Organizing On StackPanel
问题描述
我知道有一些帖子询问动态添加按钮,但我无法找到如何在 stackpanel
上组织它们.添加新按钮没有问题,但有什么方法可以按列和行组织它们吗?
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 adding new buttons but is there any way to organize them in column and row?
<Grid Margin="400,0,0,0">
<StackPanel x:Name="stackpanel">
<Button x:Name="Button" Height="30" Width="100" Content="Button" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="20,20,0,0" Click="Button_Click"/>
</StackPanel>
</Grid>
private void Button_Click(object sender, RoutedEventArgs e)
{
Button b = new Button(); ;
stackpanel.Children.Add(b);
b.Content = "Button";
}
请帮忙.谢谢.
更新:我想根据按钮被点击的次数添加按钮.它添加到第 4 个 rom 然后移动到下一个/新列.
Update: I'd like to add button(s) based on how many times the button is clicked. It adds until 4th rom then move to the next/new column.
推荐答案
根据我的评论,也可以使用 Grid
.要实现所需的布局,您可以使用以下内容:
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:
<Grid Margin="400,0,0,0">
<Grid x:Name="myGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Button x:Name="addBtn" Height="30" Width="100" Content="Button" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="20,20,0,0" Click="Button_Click"></Button>
</Grid>
</Grid>
我用 Grid
替换了你的 StackPanel
并添加了四行和第一列的定义.
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;
然后我们需要改变Button_Click
方法:
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.
这篇关于UWP C# 动态添加按钮并在 StackPanel 上组织的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!