我目前正在测试一个应用程序以列出例如产品,但存在无法使用相应内容动态生成网格的问题(目前仅适用于标签)。我想在调用主页时立即生成它们。
我已经遍历了各种教程和网站,但是找不到任何可以帮助我解决问题的东西。尝试通过将其分配给按钮来启动创建网格的方法。我曾尝试将方法分配给MainPage类的构造函数,但最终结果中仍然不会显示任何内容。
public void CreateDummyGrids()
{
Grid gOut = new Grid();
gOut.RowDefinitions.Add(new RowDefinition());
gOut.RowDefinitions.Add(new RowDefinition());
gOut.RowDefinitions.Add(new RowDefinition());
gOut.ColumnDefinitions.Add(new ColumnDefinition());
gOut.ColumnDefinitions.Add(new ColumnDefinition());
for (int rowIndex = 0; rowIndex < 3; rowIndex++)
{
for (int columnIndex = 0; columnIndex < 2; columnIndex++)
{
var label = new Label
{
Text ="Hello",
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
gOut.Children.Add(label, columnIndex, rowIndex);
}
}
}
答案 0 :(得分:1)
Grid gOut
是CreateDummyGrids
方法的局部变量,不会传递给其他任何地方。因此,使用该方法后,它将被销毁。
您需要在XAML中包含某种元素才能将网格添加到其中(或只是将网格放置在那里并将子代直接添加到其中)。
因此,在要显示网格的位置添加以下内容:
<Grid x:Name="productGrid" />
然后将您的CreateDummyGrids
更改为此:
public void CreateDummyGrids()
{
productGrid.RowDefinitions.Add(new RowDefinition());
productGrid.RowDefinitions.Add(new RowDefinition());
productGrid.RowDefinitions.Add(new RowDefinition());
productGrid.ColumnDefinitions.Add(new ColumnDefinition());
productGrid.ColumnDefinitions.Add(new ColumnDefinition());
for (int rowIndex = 0; rowIndex < 3; rowIndex++)
{
for (int columnIndex = 0; columnIndex < 2; columnIndex++)
{
var label = new Label
{
Text ="Hello",
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
productGrid.Children.Add(label, columnIndex, rowIndex);
}
}
}
现在请记住,每次调用此方法时,都会添加新的ColumnDefinitions,RowDefinitions和Labels,因此,如果要继续添加内容,则必须稍作更改。但我希望这足以使您朝正确的方向