简体   繁体   中英

WPF - duplicating a stackpanel

i have this (a rough eg):

<StackPanel>
    <StackPanel Orientation="Horizontal">
        <Label .../>
        <TextBox .../>
        <Button Content="Add new input row" ... />
    </StackPanel>
</StackPanel>

pretty self explanatory, i want to add a new Horizontal StackPanel with every click on the button..

is that possible?

thank you!

Yes it is possible try handling the event like this for example:

    // Create your StackPanel.
    StackPanel sp = new StackPanel();
    sp.Orientation = Orientation.Horizontal;
    // Add controls to new StackPanel
    // Control con = new Control();
    // sp.Children.Add(con);

    // Add created control to a previously created (and named) container.
    myStackPanel.Children.Add(sp);

If you would like your StackPanel to contain some controls you can also add them to it here.

There is a way to do this via XamlReader as well, but I have never tried it.

Here is a link to a short article:

arcanecode.com

For this XAML above I will do like this:

In the click event handle of every button name "Add new input row", I mean you can use this event for all of buttons.

private void btn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            StackPanel stkButtonParent = btn.Parent as StackPanel;
            StackPanel stkCover = stkButtonParent.Parent as StackPanel;
            StackPanel newRow = NewRow();
            stkCover.Children.Add(newRow);
        }

        private StackPanel NewRow() {
            StackPanel stk = new StackPanel();
            stk.Orientation = Orientation.Horizontal;
            Label lbl = new Label();
            lbl.Foreground = Brushes.Red; // some attribute
            TextBox txt = new TextBox();
            txt.Background = Brushes.Transparent; // some attribute
            Button btn = new Button();
            btn.Content = "Add new row";
            btn.Click += btn_Click;
            stk.Children.Add(lbl);
            stk.Children.Add(txt);
            stk.Children.Add(btn);
            return stk;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM