Search code examples
c#wpfbuttonstackpanel

how to wrap dynamic button in stackpanel programmatically? [WPF]


I would like to add 16 button in the form of 4 rows and 4 columns programmatically in a stack panel. When I add my buttons in stack panel I can view only 4 button in it. I am unable to wrap it. I don't want to use wrap panel to resolve the issue.(Wrap panel cause issue when window maximize).

Here is my code,

 foreach (var buttonName in list)
 {
   Button newButton = new Button(){Content = "button_name"};
   this.mainPanel.Children.Add(newButton);
 }

XML,

<StackPanel x:Name="mainPanel" Orientation="Horizontal"/>

Solution

  • This is all you need :

     UniformGrid g = new UniformGrid(){ Rows = 4, Columns = 4};
            g.Children.Add(new Button());
            ... add your 16 buttons ...
    

    UniformGrid knows how to present its content as (Rows x Columns).