Dynamically adding buttons to the Grid StackPanel

Tell me how to add buttons to the Grid of the StackPanel element Grid. My code:

<StackPanel Grid.Row="2" Width="350" Height="50" Name="ButtonsPanel" Background="#99000000" Orientation="Horizontal" SnapsToDevicePixels="True">
        <Grid>
             <Grid.RowDefinitions>
                  <RowDefinition Height="50" />
             </Grid.RowDefinitions>
             <Grid.ColumnDefinitions>
                  <ColumnDefinition Width="350" />
             </Grid.ColumnDefinitions>
             <!-- Put buttons here. -->
        </Grid>
   </StackPanel>

If I statically register the buttons in the StackPanel, then everything works fine. The buttons perceive HorizontalAlignment and Margin. But the number of buttons is determined depending on the conditions and the static option is no longer suitable. And if I add them programmatically, the buttons are not displayed. If I remove the Grid grid from the StackPanel, then the buttons are all collected in a heap by left edge.

I add it like this:

var button = new Button
{
    Name = "testButton",
    Content = "Test 1",
    Width = 80,
    Margin = new Thickness(0, 10, 0, 0),
    Style = (Style) Application.Current.FindResource("Flat"),
    VerticalAlignment = VerticalAlignment.Top,
    HorizontalAlignment = HorizontalAlignment.Center,
};

this.ButtonsPanel.Children.Add(button);

Naturally, the number of buttons is different, and the parameters HorizontalAlignment and Margin change depending on the number of buttons.

 1
Author: Андрей NOP, 2019-10-08

1 answers

It turned out to be very simple. You just had to specify x.Name for the Grid and refer to it, not to the StackPanel. The problem description was found only in English on MSDN.

Now the code looks like this:

<StackPanel Grid.Row="2" Width="350" Height="50" Name="ButtonsPanel" Background="#99000000" Orientation="Horizontal" SnapsToDevicePixels="True">
        <Grid x.Name="BlaBlaBLa">
             <Grid.RowDefinitions>
                  <RowDefinition Height="50" />
             </Grid.RowDefinitions>
             <Grid.ColumnDefinitions>
                  <ColumnDefinition Width="350" />
             </Grid.ColumnDefinitions>
             <!-- Put buttons here. -->
        </Grid>
   </StackPanel>

And the add code:

var button = new Button
{
    Name = "testButton",
    Content = "Test 1",
    Width = 80,
    Margin = new Thickness(0, 10, 0, 0),
    Style = (Style) Application.Current.FindResource("Flat"),
    VerticalAlignment = VerticalAlignment.Top,
    HorizontalAlignment = HorizontalAlignment.Center,
};

this.BlaBlaBLa.Children.Add(button);

Maybe someone will need it.

 1
Author: Rootware, 2019-10-08 15:07:19