سؤال

I need to create textbox dynamically and add it into stackpanel:

There is a gap between textboxes stacking ontop each other.

When a button is clicked, it will create the textbox and add it in dynamically.

Thanks

<StackPanel 
    Orientation="Horizontal" 
    HorizontalAlignment="Left" 
    Height="130"
    Margin="90,190,0,0" 
    VerticalAlignment="Top" 
    Width="1190">

</StackPanel>
هل كانت مفيدة؟

المحلول

You should edit your XAML firstly, StackPanel have to got a name, otherwise you can't reach it from C#:

<StackPanel x:Name="MyStackPanel" 
Orientation="Horizontal" 
HorizontalAlignment="Left" 
Height="130"
Margin="90,190,0,0" 
VerticalAlignment="Top" 
Width="1190">

And you can also catch event for the dynamically created objects.

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
}

نصائح أخرى

Try this

xaml

<StackPanel x:Name="StackPanel1" >
</StackPanel>

code

TextBox txt1 = new TextBox() { Text = "txt1" };
TextBox txt2 = new TextBox() { Text = "txt2" };
StackPanel1.Children.Add(txt1);
StackPanel1.Children.Add(txt2);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top