如何从Windows Phone 8.1中动态添加的文本框中获取数据?

时间:2015-07-01 06:42:20

标签: c# xaml windows-phone-8 windows-phone-8.1

我正在开发一款应用。在这里我想从动态添加的文本框中获取数据。以下是我的代码

for (int i = 0; i < result.Count; i++)
    {

        TextBox TxtBoxU = new TextBox() { Width = 30 };

        TextBox TxtBoxE = new TextBox() { Width = 20 };

        RadioButton radioButton1 = new RadioButton();


        RadioButton radioButton2 = new RadioButton();

        TextBlock tb1 = new TextBlock();
        TextBlock tb2 = new TextBlock();
        TextBlock tb3 = new TextBlock();

        TxtBoxU.Name = "TextBoxU" + i.ToString();
        TxtBoxE.Name = "TextBoxE" + i.ToString();


        tb1.FontSize = 20;
        tb2.FontSize = 20;
        tb3.FontSize = 20;

        tb1.Name = "tb1" + i.ToString();
        tb2.Name = "tb2" + i.ToString();
        tb3.Name = "tb3" + i.ToString();

        tb1.Text = "name " + (i + 1).ToString() + " : ";
        tb2.Text = "Age : ";
        tb3.Text = "Gender : ";
        radioButton1.Content = "Male";
        radioButton1.GroupName = "Gender";
        radioButton2.Content = "Female";
        radioButton2.GroupName = "Gender";

        MyStackPanel.Children.Add(tb1);
        MyStackPanel.Children.Add(TxtBoxU);

        MyStackPanel.Children.Add(tb2);
        MyStackPanel.Children.Add(TxtBoxE);

        MyStackPanel.Children.Add(tb3);
        MyStackPanel.Children.Add(radioButton1);
        MyStackPanel.Children.Add(radioButton2);

    }

在上面的代码中我想从TxtBoxU1,TxtBoxE1,TxtBoxU2,TxtBoxE2,......等等获取文本

如何从文本框中获取数据

提前致谢

2 个答案:

答案 0 :(得分:1)

您可以遍历MyStackPanel.Children,因为它是regular collection(实现IEnumerable)。

        foreach (var child in MyStackPanel.Children)
        {
            if (!(child is TextBox))
            {
                continue;
            }
            var textbox = child as TextBox;
            if (textbox.Name == "TextBoxU1")
            {
                var text = textbox.Text; //whatever you want to do here
            }
        }

但我建议您阅读DataBindingMVVM pattern

答案 1 :(得分:0)

这可以通过多种方式完成。

  1. 您可以使用VisualTreeHelper向下钻取。
  2. 您也可以尝试以下

    TextBox tb = MyStackPanel.Children [1] as TextBox;

  3. 索引与您输入的顺序相同。