简体   繁体   中英

Creating a textbox in xaml through xaml.cs code

I want to create textboxes in xaml file upon a button click through the .xaml.cs file from a loop (probably). I've calculated the margins for each textbox to appear in the panel but do not know how to bind the code. Here's the image of the xaml design view and what I'm trying to achieve. The window will have one textbox for choices appear and the loop will create another and another each time the add choice button is clicked.

Can anyone please help? I'm just learning wpf. Thank you

Assuming by Bind the code you mean how to add the TextBox to the panel. To do that, you need to add the textboxes to the Children property of the panel.

If you need to do this upon initialization of your form, then just place your code after InitializeComponent(); in the form constructor.

Here's an example how to do this programatically, responding to a click event:

Xaml:

<StackPanel Name="pn_Content" Orientation="Vertical">
    <Button Click="btn_Add_TextBox_Click">Add Textbox</Button>
</StackPanel>

C#:

private void btn_Add_TextBox_Click(object sender, RoutedEventArgs e) {
   TextBox tb = new TextBox();
   tb.Height = 23;
   tb.Width = 100;
   pn_Content.Children.Add(tb);
}

and that's it.

First, place all the current text boxes in a container, for example a stack panel named stackPanel. Then add your controls to the Children of the panel:

stackPanel.Children.Add(new TextBox { Text = "TextBox" });

please refer to these questions:

WPF: How to dynamically Add Controls in dynamically created WPF Window

Adding child controls in Stackpanel WPF C#

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