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";
}
Please help. Thanks.
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.
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 aGrid
and added definitions for the four rows and the first column.CS:
First we need to add a counter:
Then we need to change the
Button_Click
method:Inside this method, the position of the new button is automatically calculated and if needed, a new column is added to the grid.
Try this:
If you need to have a button at the beginning, when you initialize your view do the following:
Then, everytime you click on it will put a new button in the grid. Let me know if you have any other questions about this :)
As commented
Uwp
doesn't includeUniformGrid
if you don't specify it in your xaml. If you want to use it, just include this:and your
UniformGrid
will be like this: