我需要动态创建文本框并将其添加到stackpanel:
文本框之间存在间隙,彼此叠加。
单击按钮时,它将创建文本框并动态添加。
由于
<StackPanel
Orientation="Horizontal"
HorizontalAlignment="Left"
Height="130"
Margin="90,190,0,0"
VerticalAlignment="Top"
Width="1190">
</StackPanel>
答案 0 :(得分:3)
你应该首先编辑你的XAML,StackPanel必须得到一个名字,否则你无法从C#中找到它:
<StackPanel x:Name="MyStackPanel"
Orientation="Horizontal"
HorizontalAlignment="Left"
Height="130"
Margin="90,190,0,0"
VerticalAlignment="Top"
Width="1190">
您还可以捕获动态创建的对象的事件。
TextBox myTextBox = new TextBox() { Text = "txt1", Width=100, Height=40, FontSize=26};
myTextBox.TextChanged += myTextBox_TextChanged;
StackPanel1.Children.Add(myTextBox);
void myTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
//Catch myTextBox's TextChanged Event
}
答案 1 :(得分:2)
试试这个
XAML
<StackPanel x:Name="StackPanel1" >
</StackPanel>
代码
TextBox txt1 = new TextBox() { Text = "txt1" };
TextBox txt2 = new TextBox() { Text = "txt2" };
StackPanel1.Children.Add(txt1);
StackPanel1.Children.Add(txt2);