Click here to Skip to main content
15,748,049 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello can I ask a question? I tried to add Columns at StackPanel, but I've not idea, how to make this solution work.

        <StackPanel x:Name="sp">
            <Grid x:Name="GridPanel" Grid.Row="0" Grid.Column="0">
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>

TextBox tb = new TextBox();
            tb.Height = 60;
            tb.Width = 100;
            Grid.SetRow(tb, 0);
            Grid.SetColumn(tb, 0);
            Button b = new Button();
            b.Content = "Button";
            b.Width = 100;
            b.Height = 60;
            b.Click += new RoutedEventHandler(new_but);

How to add columns to it, I used this.sp.Children.Add
Updated 27-Jul-15 20:13pm
Abhijit Jana 28-Jul-15 2:12am    
Why do you need that ? You can use Grid only instead ? You are looking for anything specific to be done with Stack Panel ?
Afzaal Ahmad Zeeshan 28-Jul-15 2:14am    
Even if he does look around, StackPanel won't allow creating multiple columns in it. Using margins to align the controls relative to their actual position would ruin the layout. Please see Solution 1 for a possible solution for adding columns.

StackPanel doesn't support columns, it has only one column that can be stacked horizontally or vertically. Grid (which you are indeed using) supports columns and rows. Your code doesn't even refer to the Grid for adding the columns.

Your code, is almost there. Here have a look below,

sp.Children.Add(UIElement); // Adds a new element "in the stack"

Whereas you need to use this code,

foreach (var child in sp.Children) {
   // check the type of children
   if(child is Grid) {
      // the grid, which supports columns.
      // Now, add columns to the "child".

Read this post to learn how to add columns and rows to Grid programmatically.[^]

Now, when you will alter the definition of child, it would alter the grid that is present inside the StackPanel. Can I ask, why are you even using a StackPanel when everything has to be in a Grid. Grid is already present as a parent for this StackPanel.
Share this answer
I just wrote a 600 code in the program all built dynamically. And you say why stakpanel instead grid. Because I did not know that everything will turn so! just had to add one Knop near textbox to change the database
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900