如何获取文本框的(在堆栈面板上)值并使用循环将它们放入数组中?

How to get textboxes' (On stackpanel) values and put them into array using a loop?

我正在创建一个文本框矩阵,然后我想在这些文本框中输入一些值。之后通过单击我的矩阵下方的按钮,程序应该获取值(这是主要问题!)我想我可以使用 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...
        }
    }
}

您要向 mainPanel 添加一些 StackPanel,然后向该 stackPanel 添加文本框。

但是这里:

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
             }
        }
    }
}