如何获取文本框' (在stackpanel上)值并使用循环将它们放入数组中?

时间:2015-01-30 13:13:18

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

我正在创建一个文本框矩阵,然后我想在这些文本框中输入一些值。之后点击矩阵下方的按钮,程序应该得到值(这是主要的问题!)我想我可以使用foreach UIElement来实现它但它不起作用...我附加了一个截图和代码,请更正!

private void vsematrici_SelectionChanged(object sender, SelectionChangedEventArgs e)
{

    int selectedIndex = vsematrici.SelectedIndex + 2;
    StackPanel[] v = new StackPanel[selectedIndex];
    for (int i = 0; i < selectedIndex; i++)
    {
        v[i] = new StackPanel();
        v[i].Name = "matrixpanel" + i;
        v[i].Orientation = Orientation.Horizontal;

        TextBox[] t = new TextBox[selectedIndex];
        for (int j = 0; j < selectedIndex; j++)
        {
            t[j] = new TextBox();
            t[j].Name = "a" + (i + 1) + (j + 1);
            t[j].Text = "a" + (i + 1) + (j + 1);
            v[i].Children.Add(t[j]);

            Thickness m = t[j].Margin;
            m.Left = 1;
            m.Bottom = 1;
            t[j].Margin = m;

            InputScope scope = new InputScope();
            InputScopeName name = new InputScopeName();
            name.NameValue = InputScopeNameValue.TelephoneNumber;
            scope.Names.Add(name);
            t[j].InputScope = scope;
        }
        mainpanel.Children.Add(v[i]);

    }
    Button button1 = new Button();
    button1.Content = "Найти определитель";
    button1.Click += Button_Click;
    mainpanel.Children.Add(button1);

}

private void Button_Click(object sender, RoutedEventArgs e)
{
    myresult.Text = "After button clicking there should be shown a matrix of texboxes values";

    foreach (UIElement ctrl in mainpanel.Children)
    {
        if (ctrl.GetType() == typeof(TextBox))
        {
            //There should be a a two-dimensional array that I want to fill with textboxes' values
            //But even this "if" doen't work!!! I don't know why...
        }
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

您正在向StackPanel添加一些mainPanel,然后您将文本框添加到该stackPanels。

但是在这里:

foreach (UIElement ctrl in mainpanel.Children)
{
    if (ctrl.GetType() == typeof(TextBox))
    {

您正试图找到这些文本框,因为他们是mainPanel的孩子 - 当然,您无法通过这种方式找到它们。

因此,您可以根据您的逻辑更改代码:

foreach (UIElement pnl in mainpanel.Children)
{
    if (pnl is StackPanel)
    {
        foreach (UIElement ctrl in (pnl as StackPanel).Children)
        {
             if (ctrl is TextBox)
             {
               // your logic here
             }
        }
    }
}