动态创建TextBox名称和位置问题

时间:2013-12-23 11:09:22

标签: c# wpf dynamic textbox

我已经完成了我提出的问题,感谢所有回答的人。

在我的应用程序中,我有两个按钮可以创建我的TextBox并将它们放到我希望它们去的位置。

C#代码:

private void btnAddTitle_Click(object sender, RoutedEventArgs e)
{
        TextBox x = new TextBox();
        x.Name = "new_textbox";
        x.TextWrapping = TextWrapping.Wrap;
        x.Height = 25;
        x.Width = 200;
        x.AcceptsReturn = true;
        x.Margin = new Thickness(10, 15, 950, 0);
        spStandard.Children.Add(x);
 }

 private void btnQuestion_Click(object sender, RoutedEventArgs e)
 {
        TextBox x = new TextBox();
        x.Name = "new_textbox";
        x.TextWrapping = TextWrapping.Wrap;
        x.Height = 25;
        x.Width = 200;
        x.AcceptsReturn = true;
        x.Margin = new Thickness(10, 15, 850, 0);
        spStandard.Children.Add(x);
 }

XAML代码:

<Button x:Name="btnAddTitle" Content="Add Title" HorizontalAlignment="Left" Margin="919,30,0,0" VerticalAlignment="Top" Width="121" Height="24" Background="{x:Null}" Click="btnAddTitle_Click"/>
<Button x:Name="btnQuestion" Content="Add Question" HorizontalAlignment="Left" Margin="1080,30,0,0" VerticalAlignment="Top" Width="121" Height="24" Click="btnQuestion_Click"/>

<Rectangle Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="1" Margin="22,82,0,0" Stroke="Black" VerticalAlignment="Top" Width="1200"/>
<Border CornerRadius="6" BorderBrush="Black" BorderThickness="2" Margin="34,132,33,72">
        <StackPanel x:Name="spStandard" HorizontalAlignment="Left" Margin="0,-2,-2,-2" Width="1181"/>
</Border>

行动中的代码图片:

http://i.stack.imgur.com/REWTe.png

(标题文本框更接近边框,问题TextBoxs有差距)

已回答我的第一个问题是:当我点击按钮时,它会动态创建不同的TextBox。如何为他们提供不同的名称/ ID,以便我可以在以后需要时从该TextBox中获取信息?

我的最后一个问题是:当我编辑TextBox(x.Width = 200;)的宽度以便用户可以添加更大的问题时,TextBox会丢失位置以及边距。< / p>

照片:

http://i.stack.imgur.com/JKhUH.png

(当我做大的时候,它似乎失去了边缘,也削减了TextBox的边缘)

1 个答案:

答案 0 :(得分:1)

对于第一个问题,您可以动态生成文本框名称。

int y = 0;

        private void btnAddTitle_Click(object sender, RoutedEventArgs e)
        {
            TextBox x = new TextBox();
            x.Name = "new_textbox" + y;
            x.TextWrapping = TextWrapping.Wrap;
            x.Height = 25;
            x.Width = 200;
            x.AcceptsReturn = true;
            x.Margin = new Thickness(10, 15, 950, 0);
            spStandard.Children.Add(x);
            y++;
        }