简体   繁体   English

在C#WPF应用程序中加载Window时如何将TextBox插入Grid

[英]How to insert TextBox into Grid when Window is loaded in C# WPF application

private void Window_Loaded(object sender, RoutedEventArgs e)
{  
    for (int i = 0; i <= 7; i++)
    {
        ColumnDefinition clDef = new ColumnDefinition();
        RowDefinition rwDef = new RowDefinition();
        clDef.MinWidth = 40;
        clDef.MaxWidth = 40;
        rwDef.MinHeight = 32;
        rwDef.MaxHeight = 32;
        grdAdtn.ColumnDefinitions.Add(clDef);
        grdAdtn.RowDefinitions.Add(rwDef);
    };
    TextBox[,] fields=new TextBox[8,8];
    for(int i=0;i<=7;i++){
        for(int j=0;j<=7;j++){
            fields[i,j]=new TextBox();
            fields[i, j].Text = "test";
            fields[i, j].Width = 40;
            fields[i, j].Height = 32;
            fields[i, j].Visibility = Visibility.Visible;
            //Grid.SetColumn(fields[i, j], i);
        }
    }
}

With this I managed to add rows and columns to grid but I don't see textboxes in grid fields. 这样,我设法向网格中添加行和列,但是在网格字段中看不到文本框。 I need to make an array of textboxes so I can access them later and I don't know how to make control array in Visual Studio editor so I tried to make the array when application is running. 我需要制作一个文本框数组,以便以后可以访问它们,而且我不知道如何在Visual Studio编辑器中制作控件数组,因此我尝试在应用程序运行时制作该数组。 Sorry for bad English. 对不起,英语不好。

Where you have commented out the SetColumn you need the following three lines: 在注释掉SetColumn的地方,需要以下三行:

grdAdtn.Children.Add(fields[i,j]);  
Grid.SetColumn(fields[i,j], i);  
Grid.SetRow(fields[i,j], j);  

So you were on the right track you just hadn't added the text boxes to the design - all you'd done was create them and tried to set a column property. 因此,在正确的轨道上,您只是没有在设计中添加文本框-您要做的就是创建文本框并尝试设置column属性。

Also note it's best to avoid single letter variables - row and col for example would make this easier to read. 另请注意,最好避免使用单个字母变量-例如,row和col将使其更易于阅读。

There may be another way to approach the problem as a whole but this will get your code working 可能有另一种方法可以解决整个问题,但这将使您的代码正常工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM