简体   繁体   English

WPF-复制堆栈面板

[英]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.. 很好的自我解释,我想在每次单击按钮时添加一个新的Horizo​​ntal StackPanel。

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. 如果您希望StackPanel包含一些控件,也可以在此处将其添加到其中。

There is a way to do this via XamlReader as well, but I have never tried it. 也可以通过XamlReader来执行此操作,但是我从未尝试过。

Here is a link to a short article: 这是短文章的链接:

arcanecode.com arcanecode.com

For this XAML above I will do like this: 对于上面的XAML,我将这样做:

In the click event handle of every button name "Add new input row", I mean you can use this event for all of buttons. 在每个按钮名称为“添加新输入行”的click事件句柄中,我的意思是您可以对所有按钮使用此事件。

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;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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